5

I have this code

import com.fasterxml.jackson.annotation.JsonProperty
import org.json4s.DefaultFormats
import org.json4s.jackson.Serialization.{read, write}

object Testing extends App {
    implicit val formats = DefaultFormats
    val json =
            """
              |{
              |"1strange_field_name":"name"
              |}
            """.stripMargin
    println(read[Test](json))
}

case class Test(@JsonProperty("1strange_field_name") testName: Option[String])

It should be printing Test(Some(name)) but it's printing Test(None). This is caused by the fact that json4s is not using the @JsonProperty annotation. Is there a way to configure json4s to use the jackson annotations?

Mikel San Vicente
  • 3,831
  • 2
  • 21
  • 39

1 Answers1

0

I've found that the easiest way to solve this is to use the exact field name by using ``

case class Test(`1strange_field_name`: Option[String])
bashan
  • 3,572
  • 6
  • 41
  • 58
Mikel San Vicente
  • 3,831
  • 2
  • 21
  • 39
  • 1
    Not sure I understand why not simply use: 1strange_field_name without ``. It doesn't actually answer the question. The whole point is to use a different naming convention in the scala code and when creating the JSON itself – bashan Feb 18 '20 at 13:31
  • it is my own question... so I think I understand it – Mikel San Vicente Feb 18 '20 at 13:51
  • 1strange_field_name is an invalid identifier is Scala – Mikel San Vicente Feb 18 '20 at 14:08
  • This works good: case class Test(1strange_field_name: Option[String]). It will use the name of the case class property as the field of the JSON. No need for ``. Anyway, The whole point, as also written in your own code is to have a JSON field with a name different than the case class property name (using @JsonProperty). – bashan Feb 19 '20 at 19:18
  • 1
    No ofense, but please don't explain me my own quetion... the whole point was to be able to parse the json into a case class without having to write a custom parser. `case class Test(1strange_field_name: Option[String])` does not compile in Scala 2.10, 2.11, 2.12 or 2.13 so I am not sure how are you compiling your code – Mikel San Vicente Feb 20 '20 at 07:44