so let's assume that we have two systems (system A and system B) that exchange information in JSON, however, the guys from System B do not want to be really cooperative and claim that everything with their payload is fine because it is "syntactically" correct JSON.
Now let's assume that you have the following json structure
{
"INFO": {
"Animal": {
"Cat": {}
}
}
}
This is really a valid JSON, but the thing is you can have one or more animals, so in the scenario of more animals the payload is:
{
"INFO": {
"Animal": [{
"Cat": {},
"Dog" :{}
}]
}
}
Only this time as you can see the Animal object is actually an array of objects...so System A uses RestTemplate to parse the response and has problems since the "syntactically" correct JSON differs in structure each time. Moreover, ERRORS might occur in the JSON as well - in case of errors the JSON looks like : "ERRORS" : {[error1, error2, etc.]},
but in case of no errors it comes as
"ERRORS" : ""
So tell me please, am I wrong for wanting the payload to be consistent and get like always an array of objects, no matter one or many, and getting no errors node in case of no errors, or am I missing something?
I'm using RestTemplate and
when the payload comes with one Animal (my pojo expects 1 or many) -> it fails as it cannot parse a single object into array list.
if I change it to expect only one Animal - it fails when more than one comes.
More than that - the "ERRORS" : "" is treated as a String which again causes parses issues.
So is there some "hack" way to make the Jackson deserializer in RestTemplate to handle this "syntactically" correct JSON, or the overall structure of the JSON should be clarified and consistent (my opinion)
Thanks!
Looks like you want to enable DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY
in your ObjectMapper
:
ObjectMapper mapper = new ObjectMapper()
mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);