I have a pretty complex json string that I would like to deserialize into custom Java Pojo, but Im not so sure how to do it.
Here is the json:
{
"A": {
"view": {
"1": ["stringA", "stringB"],
"2": ["stringA", "stringB"],
"3": ["stringA", "stringB"]
},
"list": ["stringA", "StringB"]
},
"B": {
"view": {
"1": ["stringA", "stringB"],
"2": ["stringA", "stringB"],
"3": ["stringA", "stringB"]
},
"list": ["stringA", "StringB"]
}
}
Notice that view
key has an extra nesting comparing to list
.
Any help would be great!
EDIT2:
Let's try to reduce my question into a simpler JSON as follow:
{
"view": {
"1": ["stringA", "stringB"],
"2": ["stringA", "stringB"],
"3": ["stringA", "stringB"]
},
"list": ["stringC", "stringD"]
}
Here is my Pojo:
public class Model {
private final Map<String, List<String> modelView;
private final List<String> modelList;
@JsonCreator
public ModelView(@JsonProperty("view") Map<String, List<String>>
modelView, @JsonProperty("list") List<String> modelList) {
this.modelView = modelView;
this.modelList = modelList;
}
public Map<String, List<String>> getModelView() {
return modelView;
}
public List<String> getModelList() {
return modelList;
}
}
and my test code:
@Test
public void testSerialization() throws Exception {
try {
JSONObject json = new JSONObject(json1Str());
ObjectMapper mapper = new ObjectMapper();
Model model = mapper.readValue(json.toString(), Model.class);
System.out.println(model.getModelView());
} catch (Exception e) {
e.printStackTrace();
}
}
It doesn't work...any thoughts on that?
To deserialize the JSON with dynamic keys you can use the @JsonAnySetter annotation from the Jackson library. It will add your keys to values mapping into the Java Map.