Search code examples
jsonscalajson4s

scala - how to change field names when decomposing with json4s?


With Json Play when I wanted to return Json representation of SalesData with custom field names I did it with the help of Writes as shown below. Is it possible to achieve the same result with Json4s? I have read from the documentation that By default the constructor parameter names must match json field names.

Here is how I did it with Play framework:

object SalesProcessor {
    case class SalesData(saleId: Int, saleType: String)
    implicit val saleReads: Reads[SalesData] = (
        (JsPath \ "saleId").read[Int] and
        (JsPath \ "saleType").read[String]
    ) (SalesData.apply _)

    implicit val saleWrites: Writes[SalesData] = (
       (JsPath \ "id").write[String] and
         (JsPath \ "type").write[String]
       ) (unlift(SalesData.unapply))

    val rawJson: String = Source.fromURL("https://mytest.com/api/sales.json").mkString
    val salesJson: JsValue = Json.parse(rawJson)
    val salesData: List[SalesData] = salesJson.as[List[SalesData]]

    def salesToJsValue(salesData: SalesData): JsValue = {
       Json.toJson(salesData)
     }
}

But how can I give different field names when decomposing?

def salesToJsValue(salesData: SalesData): JValue = {
           Extraction.decompose(salesData)
         }

Solution

  • In order to create custom naming with json4s you need to use a Custom Format.

    import org.json4s.{DefaultFormats, Extraction, FieldSerializer, Formats}
    import org.json4s.FieldSerializer._
    import org.json4s.native.Serialization.{read, write}
    
    val rename = FieldSerializer[SalesData](
      renameTo("saleId", "id").orElse(renameTo("saleType", "type"))
    )
    
    implicit val format: Formats = DefaultFormats + rename
    
    
    val result = Extraction.decompose(SalesData(1, "NEW"))
    

    https://github.com/json4s/json4s#serializing-fields-of-a-class