2

I am trying to parse JSON data using Jackson, found that instance some time as array or String

JSON DATA instance with String :

{
  "Value" : "1"
}

JSON DATA instatnce with Array :

{
  "Value" : ["ram","kumar"]
}

due to this getting error are given below

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot 
deserialize instance of `java.util.ArrayList` out of VALUE_STRING token

In this case how to solve this,thankyou

current java code

ObjectMapper objectMapper = new ObjectMapper(); 
try { 
     String jsonInString = objectMapper.writeValueAsString(products.get(j)); 
       InventoryParser inventoryParser = 
        objectMapper.readValue(jsonInString, InventoryParser.class); 
        System.out.println(inventoryParser.getName()); 
      } 
       catch (IOException e) 
       { 
         e.printStackTrace(); 
        } 
    }
S Mugunthan kumar
  • 177
  • 1
  • 2
  • 11

2 Answers2

0

Read into a map data structure like so and then process it.

final Map<String, Object> result = new ObjectMapper().readValue(jsonStr,
        new TypeReference<Map<String, Object>>() {
        });
Ravindra Ranwala
  • 20,744
  • 6
  • 45
  • 63
0

You can write a custom deserializer and write custom logic to handle such data. In the deserializer you can check whether the node is an array or not.

Please refer deserialize xml to pojo using jackson xml mapper (The example is in XML but can be similarly used for JSON too by using ObjectMapper)

S.K.
  • 3,597
  • 2
  • 16
  • 31