Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Parsing JSON in Jackson library would require:

  • for an object

    MapType hashMapType = typeFactory.constructMapType(HashMap.class, String.class, Object.class);
    Map<String, Object> receivedMessageObject =  objectMapper.readValue(messageBody, hashMapType);
    
  • for an array of objects

    Map[] receivedMessage = objectMapper.readValue(messageBody, HashMap[].class)
    

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?

like image 825
onkami Avatar asked Oct 18 '25 17:10

onkami


2 Answers

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.

like image 128
ryanp Avatar answered Oct 21 '25 09:10

ryanp


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

like image 20
Magd Kudama Avatar answered Oct 21 '25 09:10

Magd Kudama