Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson ObjectMapper ignore all properties that has no annotation

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.

like image 619
IntoTheDeep Avatar asked Oct 04 '16 11:10

IntoTheDeep


People also ask

How to ignore unknown fields in JSON in objectmapper?

At the ObjectMapper level using configure () method. Method 1: Using @JsonIgnoreProperties If a Model class is being created to represent the JSON in Java, then the class can be annotated as @JsonIgnoreProperties (ignoreUnknown = true) to ignore any unknown field.

What is objectmapper in Jackson?

We've covered the ObjectMapper class - the central API of Jackson for serialization and deserialization of Java Objects and JSON data. We've first taken a look at how to install Jackson, and then dived into converting JSON to Java Objects - from strings, files, HTTP Responses, InputStreams and byte arrays.

How to ignore unknown fields in Jackson API?

Jackson API provides two ways to ignore unknown fields, first at the class level using @JsonIgnoreProperties annotation and second at the ObjectMapper level using configure () method.

How to ignore null and empty fields while writing JSON in Jackson?

Jackson provides Include.NON_NULL to ignore fields with Null values and Include.NON_EMPTY to ignore fields with Empty values. By default Jackson does not ignore Null and Empty fields while writing JSON. We can configure Include.NON_NULL and Include.NON_EMPTY at property level as well as at class level using @JsonInclude annotation.


1 Answers

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.

like image 83
cassiomolin Avatar answered Oct 28 '22 07:10

cassiomolin