I am trying to parse a JSON in the following format:
[
{
"wrapper": {
"fieldA": "testA1",
"fieldB": "testB1",
}
},
{
"wrapper": {
"fieldA": "testA2",
"fieldB": "testB2",
}
},
{
"wrapper": {
"fieldA": "testA3",
"fieldB": "testB3",
}
}
]
My Java code looks like this:
@JsonIgnoreProperties(ignoreUnknown = true)
public class Wrapper {
@JsonProperty("wrapper")
MyObject wrapper;
}
and
@JsonIgnoreProperties(ignoreUnknown = true)
public class MyObject {
@JsonProperty("fieldA")
String fieldA;
@JsonProperty("fieldB")
String fieldA;
}
This works but I don't want to use a separate class just for the wrapper element. How can I configure the MyObject
class to map the JSON structure directly?
I stumbled over the same problem. To shorten the research for others I'll add the solution to the example the author has given.
It can be done with @JsonProperty
and some simple logic.
Example:
@JsonIgnoreProperties(ignoreUnknown = true)
public class MyObject {
String fieldA;
String fieldA;
@JsonProperty("wrapper")
private void unpackNested(Map<String,Object> wrapper) {
this.fieldA = (String) wrapper.get("fieldA");
this.fieldB = (String) wrapper.get("fieldB");
}
}
Source: Jackson nested values