Java – JSON deserialization problem
There is an array. When the size is 1, the JSON data I receive does not contain []; like
{"firstname":"tom"}
When the size is greater than 1, the data I receive contains [], such as
[{"firstname":"tom"},{"firstname":"robert"}]
Currently, my class contains an array property
String[] firstname; //getter setter omit here
Code processing this like
ObjectMapper mapper = new ObjectMapper(); MyClass object = mapper.readValue(json,MyClass.class);
Deserialization works when the size is greater than 1 However, when size is 1, deserialization fails
I am currently using Jackson, any solution to this problem?
I wonder if Jackson / gson or any other library can deal with this problem?
Solution
Especially Jackson, your best choice is to bind to jsonnode or object first, such as:
Object raw = objectMapper.readValue(json,Object.class); // becomes Map,List,String etc
Then check what you get and bind again:
MyClass[] result; if (raw instanceof List<?>) { // array result = objectMapper.convertValue(raw,MyClass[].class); } else { // single object result = objectMapper.convertValue(raw,MyClass.class); }
But I think the JSON you get is terrible - why do you return an object or array with only array 1 So if possible, I'd rather fix JSON first But if this is not possible, it will work