I am receiving from the API this JSON:
"link": [],
"firstRecord": 1,
"item": [
{
"Customer": {
"id": "1058207",
"firstName": "foo",
"lastName": "foo2",
"nestedObj1": {
"id": "40008"
},
"nestedObj2": {
"link": [],
"linkfoo": "lala",
"item": [
{
"id": "266614",
"label": "NESTED_OBJ_2"
}
]
}
]
}
My Deserializer function
@Override
public CustomerView deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
//tried this too
TreeNode treeNode = p.getCodec().readTree(p);
// also this
JsonNode node = p.getCodec().readTree(p);
JsonNode simpleNode = new ObjectMapper().readTree(p);
// use for each field that is not String
ObjectMapper mapper = new ObjectMapper();
Customer customer = new Customer();
customer.setFirstName(simpleNode.get("Customer").get("firstName").textValue());
NestedObj2[] arrayObj2 = mapper.readValue(
simpleNode.get("Customer").get("nestedObj2").get("item").toString(),
NestedObj2[].class);
customer.setArrayObj2(arrayObj2);
}
Class NestedObj2 has all the fields as in the JSON, "item" array is separate object as a field.
The problem is, that neither JsonNode nor TreeNode, doesn't see field "nestedObj2", but the rest of the fields are inside them while deserializing -> checked while debugging.
Do I miss something in configuration, or should I use other object to deserialize?
Thanks!
EDIT
In the end I've used DTO as @Mehrdad HosseinNejad advised.
As I'm receiving this JSON by RestTemplate.exchange()
, I had to configure RestTemplate
with MappingJacksonHttpMessageConverter
like here https://stackoverflow.com/a/9381832/12677470