Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
wszk1992 opened this issue May 21, 2019 · 5 comments
Open

Comments

@wszk1992
Copy link

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
Copy link
Member

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
Copy link

gabrieljones commented Jun 15, 2022

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
Copy link
Member

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

@swayamraina
Copy link

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

@cowtowncoder
Copy link
Member

@swayamraina I think this is what is requested.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants