FasterXML / jackson-future-ideas

Repository for SOLE PURPOSE of issue tracker and Wiki for NEW IDEAS. Please: NO BUG REPORTS.
18 stars 6 forks source link

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

Open wszk1992 opened 5 years ago

wszk1992 commented 5 years ago

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

cowtowncoder commented 4 years ago

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.

gabrieljones commented 2 years ago

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)

cowtowncoder commented 2 years ago

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

swayamraina commented 2 years ago

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

cowtowncoder commented 2 years ago

@swayamraina I think this is what is requested.