Ignore null fields when DEserializing JSON with Gson or Jackson

I know a lot of questions about skipping fields with a zero value when serializing objects in JSON. I want to skip / ignore null fields when deserializing JSON for an object.

Consider the class

public class User { Long id = 42L; String name = "John"; } 

and json string

 {"id":1,"name":null} 

By doing

 User user = gson.fromJson(json, User.class) 

I want user.id be "1" and user.name be "John".

Is this possible with Gson or Jackson in general (without a special TypeAdapter or the like)?

+5
source share
3 answers

To skip using TypeAdapters, I would make POJO do a null check when calling the setter method.

Or look

 @JsonInclude(value = Include.NON_NULL) 

Annotations should be at the class level, not at the method level.

 @JsonInclude(Include.NON_NULL) //or Include.NON_EMPTY, if that fits your use case public static class RequestPojo { ... } 

For Deserialise, you can use the following at the class level.

@JsonIgnoreProperties (ignoreUnknown = true)

0
source

What I did in my case is set the default value for getter

 public class User { private Long id = 42L; private String name = "John"; public getName(){ //You can check other conditions return name == null? "John" : name; } } 

I suppose this will be a pain for many fields, but it works in the simple case with fewer fields

0
source

Although this is not the most concise solution, with Jackson you can deal with setting properties yourself using the custom @JsonCreator :

 public class User { Long id = 42L; String name = "John"; @JsonCreator static User ofNullablesAsOptionals( @JsonProperty("id") Long id, @JsonProperty("name") String name) { User user = new User(); if (id != null) user.id = id; if (name != null) user.name = name; return user; } } 
0
source

Source: https://habr.com/ru/post/1246559/


All Articles