onkami
onkami

Reputation: 9421

Jackson: understand if source JSON is an array or an object

Parsing JSON in Jackson library would require:

What would be the best way to check whether I have array or object in messageBody, in order to route to the correct parsing? Is it just to directly check for array token in MessageBody?

Upvotes: 4

Views: 5348

Answers (3)

Biju Gopinathan
Biju Gopinathan

Reputation: 145

This is what I did based on the answer from @ryanp :

public class JsonDataHandler {
    public List<MyBeanClass> createJsonObjectList(String jsonString) throws JsonMappingException, JsonProcessingException {
        ObjectMapper objMapper = new ObjectMapper();
        objMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
        List<MyBeanClass> jsonObjectList = objMapper.readValue(jsonString, new TypeReference<List<MyBeanClass>>(){});
        return jsonObjectList;
    }
}

Upvotes: 1

ryanp
ryanp

Reputation: 5127

An option is just to treat everything that might be an array as an array. This is often most convenient if your source JSON has just been auto-transformed from XML or has been created using an XML-first library like Jettison.

It's a sufficiently common use case that there's a Jackson switch for this:

ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);

You can then just deserialize a property into a collection type, regardless of whether it's an array or an object in the source JSON.

Upvotes: 10

Magd Kudama
Magd Kudama

Reputation: 3479

If you want to know whether your input is an array or an object, you can simply use the readTree method. A simple example:

ObjectMapper mapper = new ObjectMapper();

String json1 = "{\"key\": \"value\"}";
String json2 = "[\"key1\", \"key2\"]";

JsonNode tree1 = mapper.readTree(json1);
System.out.println(tree1.isArray());
System.out.println(tree1.isObject());

JsonNode tree2 = mapper.readTree(json2);
System.out.println(tree2.isArray());
System.out.println(tree2.isObject());

If you want to be able to deserialize to multiple types, have a look at Polymorphic Deserialization

Upvotes: 8

Related Questions