10

My target is is to convert jsonObject to Class. I want to add only fields that are anotated in Class. Example: json object holds 50 fields. Class has 4 fields. I want to map only exact 4 fields without adding 46 addition ignores in class.

JSON:

{
  "id": "1",
  "name": "John",
  "Address": "Some Address 7009",
}

Class:

public static class User {
    Integer id;
    String name;

    public User (@JsonProperty("id")Integer id, @JsonProperty("name")String name {
            this.id= id;
            this.name= name;
    }
    ....
}

User class has no address field. My target is to exclude it, because it has no annotation.

IntoTheDeep
  • 4,027
  • 15
  • 39
  • 84

1 Answers1

14

Annotate your class with @JsonIgnoreProperties, as following:

@JsonIgnoreProperties(ignoreUnknown = true)
public class User {
    ...
}

When ignoreUnknown is true, all properties that are unrecognized (that is, there are no setters or creators that accept them) are ignored without warnings (although handlers for unknown properties, if any, will still be called) without exception.

cassiomolin
  • 124,154
  • 35
  • 280
  • 359
  • It is used when any new property which is not available in class – Nimesh Oct 04 '16 at 12:07
  • TeodorKolev has 40 property in class and 40 keys in json and he wants only 4 properties converted into Java object property. Remaining should be default value like null, 0 or whatever. Providing class level annotation will not solve this issue – Nimesh Oct 04 '16 at 12:11
  • 1
    @Naman Your comments are really silly. You should read the question. – cassiomolin Oct 04 '16 at 12:14
  • @Naman I told you to read the question. I have typed that I have 4 fields in class – IntoTheDeep Oct 04 '16 at 12:14
  • You might be using old version of library. I am using latest Jackson and I don't need to mention this property manually. BDW good luck you got your answer. – Nimesh Oct 04 '16 at 12:17
  • @Naman At the time of this writing, the most recent version of Jackson is 2.8.3 (have a look [here](https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core)). I've just tested with Jackson 2.8.3 and my solution works like a charm. – cassiomolin Oct 04 '16 at 12:21
  • @CássioMazzochiMolin you are right it is always backward compatible but it is not required to add this annotation in latest version. I had also achieved this without using any annotation – Nimesh Oct 04 '16 at 12:24