Is there a way to make Jackson interpret single JSON object as an array with one element and vice versa?
Example, I have 2 slightly different formats of JSON, I need both to map to same Java object:
Format A (JSON array with one element):
points : [ { date : 2013-05-11 value : 123 }]
Format B (JSON object, yes I know it looks "wrong" but it's what I'm given):
points : { date : 2013-05-11 value : 123 }
Target Java object that both of the above should convert to:
//Data.java public List<Point> points; //other members omitted //Point.java class Point { public String date; public int value; }
Currently, only A will parse properly to Data. I want avoid directly tampering with the JSON itself. Is there some configuration in Jackson I can tamper with in order to make it accept B ?
The ToObjectCollectionSafe<TResult>() method can handle that for you. This is usable for Single Result vs Array using JSON.net and handle both a single item and an array for the same property and can convert an array to a single object.
Arrays in JSON are almost the same as arrays in JavaScript. In JSON, array values must be of type string, number, object, array, boolean or null. In JavaScript, array values can be all of the above, plus any other valid JavaScript expression, including functions, dates, and undefined.
A JsonNode is Jackson's tree model for JSON and it can read JSON into a JsonNode instance and write a JsonNode out to JSON. To read JSON into a JsonNode with Jackson by creating ObjectMapper instance and call the readValue() method. We can access a field, array or nested object using the get() method of JsonNode class.
databind. ObjectMapper ) is the simplest way to parse JSON with Jackson. The Jackson ObjectMapper can parse JSON from a string, stream or file, and create a Java object or object graph representing the parsed JSON. Parsing JSON into Java objects is also referred to as to deserialize Java objects from JSON.
Try with DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY
- it should work for you.
Example:
final String json = "{\"date\" : \"2013-05-11\",\"value\" : 123}"; final ObjectMapper mapper = new ObjectMapper() .enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY); final List<Point> points = mapper.readValue(json, new TypeReference<List<Point>>() {});
The Jackson 1.x-compatible version uses DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY
. So the above answer changes to:
final String json = "{\"date\" : \"2013-05-11\",\"value\" : 123}"; final ObjectMapper mapper = new ObjectMapper() .enable(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY); final List<Point> points = mapper.readValue(json, new TypeReference<List<Point>>() { }); System.out.println(points);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With