简体   繁体   中英

Is it possible to deserialize values missing from JSON to some default values?

As an example class:

@Getter @Setter
public static class SomeClass {
    private String notNull;
    private String nullSetEmpty;
    private String notExists;
}

Deserialization of null values to empty is possible by overriding configuration, like:

String json = " {\"notNull\": \"a value\", \"nullSetEmpty\": null}";
ObjectMapper om = new ObjectMapper();
om.configOverride(String.class)
    .setSetterInfo(JsonSetter.Value.forValueNulls(Nulls.AS_EMPTY));
SomeClass sc = om.readValue(json, SomeClass.class);
System.out.print(om.writerWithDefaultPrettyPrinter().writeValueAsString(sc));

This produces:

{
 "notNull" : "a value",
 "nullSetEmpty" : "",
 "notExists" : null
}

But how about this notExists . It is possible to add default value to each class having the problem but is there any generic way to do that like configOverride does so that Jackson handles that?

you can just define default value in your data class

@Getter
    @Setter
    public static class SomeClass {
        private String notNull;
        private String nullSetEmpty;
        private String notExists = "default-value";
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM