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(); 
        } 
    }
0

2 Answers 2

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>>() {
        });
Sign up to request clarification or add additional context in comments.

2 Comments

Here I am using POJO class, is that I need to remove as per the code you mentioned.
Just do the same as above, it should work.
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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.