0

We have a json where for a particular field the data type is different. I want to map it to Java Object using jackson. If the fields are of one type i am able to do it. but for different type unable to find a way.

{
    "firstname": "first_name",
    "age": "34",
    "add_info": [{
            "type": "type_a",
            "value": "value_a"
        },
        {
            "type": "type_b",
            "value": [{
                    "title": "info_1",
                    "desc": "desc_1"
                },
                {
                    "title": "info_2",
                    "desc": "desc_2"
                }
            ]
        }
    ]
}

POJO: Basically with this POJO i dont know how to define it

public class AddInfo {
private String type;
private List<Value> value = null;
//getter and setters
}

In the above JSON for add_info field it contains array of JSON object wherein first object value is of type string and second value holds an array of object.

How to handle this kind of situation in Pojo using jackson

3
  • 2
    Make a class for List<Value> and write a custom deserializer Commented Aug 7, 2020 at 19:58
  • Thanks for input ! How can we write the custom deserializer Commented Aug 7, 2020 at 20:11
  • 1
    baeldung.com/jackson-deserialization here you find details Commented Aug 7, 2020 at 20:15

1 Answer 1

1

If you do not want to write a custom deserializer, you could simply use an Object field:

public class AddInfo {

  public String type;
  public Object value;

  public static void main(String[] args) throws Exception {
    ObjectMapper om = new ObjectMapper();
    AddInfo i1 = om.readValue("{\"value\":\"string\"}", AddInfo.class);
    System.out.println(i1.value);
    AddInfo i2 = om.readValue("{\"value\":[{\"x\":1}]}", AddInfo.class);
    System.out.println(i2.value);
  }
}

In the first run, i1.value is a String. In the second run, i2.value is a list of hashmaps. So you loose the Pojo structure.

Sign up to request clarification or add additional context in comments.

1 Comment

list of hashmap means it will be like x as key and 1 as value

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.