Search code examples
scalasprayjson4s

how to use spray json4s support to marshal json data as snake case


Scala case class fields are camelcased,

but I want to produce json with snake case.

Is there anyway to do this ?

The Json4sSupport trait seems have no way to do this


Solution

  • A JValue has a snakizeKeys function.

    import org.json4s.jackson.JsonMethods._
    
    val json = """{
                 |  "lowerCamelCase": 100,
                 |  "UpperCamelCase": 100,
                 |  "snake_case": 100,
                 |  "dashed-case": 100,
                 |  "using spaces": 100
                 |}""".stripMargin
    
    val ast = parse(json)
    
    println(pretty(ast.snakizeKeys))
    
    //  {
    //    "lower_camel_case" : 100,
    //    "upper_camel_case" : 100,
    //    "snake_case" : 100,
    //    "dashed_case" : 100,
    //    "using_spaces" : 100
    //  }
    

    You probably want to hook the conversion in a post-processing step on the response and/or pre-processing of the request.