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

How to convert a missing list field into Nil? #386

Closed
grant-guo opened this issue Aug 3, 2018 · 3 comments
Closed

How to convert a missing list field into Nil? #386

grant-guo opened this issue Aug 3, 2018 · 3 comments

Comments

@grant-guo
Copy link

grant-guo commented Aug 3, 2018

I have the following demo codes:

case class Person(
  @JsonProperty("first") first:String,
  @JsonProperty("last") last:String,
  @JsonProperty("phones") phones: Seq[String],
  @JsonProperty("address") address:Option[String],
  @JsonProperty("cars") cars: Seq[String]
)

  val mapper = new ObjectMapper()
  mapper.registerModule(DefaultScalaModule)

  val json =
    """
      {
        "first":"grant",
        "last":"guo",
        "phones":["416", "647"],
        "address":"abc"
      }
    """.stripMargin

  val person = mapper.readValue[Person](json, classOf[Person])

In the parsed person instance, cars field is a Java null, is there any way to convert it into Nil directly?

@nbauernfeind
Copy link
Member

I'm not sure if there's a solution built-in to jackson that would treat a missing entry as an empty list. Technically a null object, empty list, and non-empty list are different scenarios one might want to detect based on the inputted json.

Work arounds you can try (I'm not sure if all will work):

  • rename cars to _cars for the variable and add a getter that converts null's to empty Seq's
  • use a JsonCreator that does this once at construction time
  • convert the Seq[String] to an Option[Seq[String]] so you know it is optionally provided.

@Phil4
Copy link

Phil4 commented Jul 5, 2019

I have the exact same issue.
It seems strange to want to handle null values in Scala immutable collections.
Anyway, as workaround I used a var instead of a val:

case class Person(
  ...
  @JsonProperty("phones") var phones: Seq[String],
  ...
) {
  phones = if(phones == null) Nil else phones
}

@pjfanning
Copy link
Member

merging with #462

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