jackson-future-ideas icon indicating copy to clipboard operation
jackson-future-ideas copied to clipboard

set default value if null (or meet some condition) in deserialization

Open wszk1992 opened this issue 5 years ago • 5 comments

I'm wondering if we can have an annotation (field level and class level) to set a default value if the corresponding JSON value is null in deserialization.

{
  "name": "Jack"
}
class People {
  String name;
  @JsonDefault(intDefault = 10)
  Integer age;
}

After deserialization, We can have people.name == "Jack" and people.age == 10.

@JsonDefault(floatDefault = 0.0f, intDefault = 0)
class People {
  String name;
  Integer age;
  Float weight;
}

After deserialization, We can have people.name == "Jack", people.age == 0 and people.weight == 0.0

wszk1992 avatar May 21 '19 15:05 wszk1992

Since Jackson 2.9, there is @JsonSetter which allows for defaulting to "empty", as well as failing (throwing exception) or skipping (leaving default value). This is explained here:

https://medium.com/@cowtowncoder/jackson-2-9-features-b2a19029e9ff

and probably covers some of the use cases.

This does not quite cover cases that might occur here but I mention it in any case anyone is looking for existing functionality.

Other than that, we have no current plans to extend value handling towards configurable defaults: the main approach is to expect POJOs to be constructed with defaults -- this coupled with Nulls.SKIP might work for most use cases.

cowtowncoder avatar Oct 21 '20 03:10 cowtowncoder

Can we have @JsonSetter(missing = Missing.AS_EMPTY)? ~or @JsonSetter(missing = Nulls.AS_EMPTY)?~ ~or @JsonSetter(missing = JsonSetter.AS_EMPTY)?~ Should also add SKIP, FAIL, and DEFAULT while we're at it. SET does not make sense like it does for Nulls. That probably means a separate Missing enum is in order. A Missing.AS_NULL might make sense too.

Then I could do @JsonSetter(nulls = Nulls.AS_EMPTY, missing = Missing.AS_EMPTY)

This would then effectively be the full inverse of @JsonInclude(JsonInclude.Include.NON_EMPTY)

gabrieljones avatar Jun 15 '22 06:06 gabrieljones

Yes, if this feature was implemented one possibility could be to use constant like that.

cowtowncoder avatar Jun 15 '22 16:06 cowtowncoder

Are we thinking of doing a @JsonDefault at a field level?

swayamraina avatar Oct 14 '22 11:10 swayamraina

@swayamraina I think this is what is requested.

cowtowncoder avatar Oct 14 '22 20:10 cowtowncoder