1

Lets take a example my object Person having 2 properties below

public class Person {

    String name;
    Integer age;

    //getters and setters
}

but jsonaray contains more than 2 properties

[{
    "name": "ab",
    "age": 18,
    "c": "dc",
    "d": "ef"
}]

Here extra elements c and d are there. Can I convert that jsonarray to set person object?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
vinay kumar
  • 91
  • 1
  • 2
  • 10

2 Answers2

3

Since we don't know which library you are using, I would go ahead and assume you are using the most common one - Jackson.

Use @JsonIgnoreProperties(ignoreUnknown = true) annotation on your Person class. This annotation allows you to ignore any field in the JSON which doesn't map to the fields in your POJO.

daniu
  • 14,137
  • 4
  • 32
  • 53
Nishit
  • 1,276
  • 2
  • 11
  • 25
1

You have got multiple options

  1. Code a JSON Parse your self(Which I hope is not the expectation here).
  2. Use frameworks/JSON parser libraries available.

One such framework is jackson. You can achieve what you need as below

public static void main(String[] args) throws Exception {

   //Step 1. Create and set properties of ObjectMapper.
   // You need FAIL for unknow properties false for your case
   ObjectMapper mapper = new ObjectMapper();
   mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
       
   String jsonStr = {
                    "name": "ab",
                    "age": 18,
                    "c": "dc",
                    "d": "ef"
                   };
       try{
            //Step 2: call mapper to convert it to your class
            Person person = mapper.convertValue(jsonStr, Data.class);
        }catch(IllegalArgumentException e){
            //log error
        }
}



Vishal T
  • 85
  • 6