camel case json to snake case json in scala/java

2.7k views Asked by At

I have a JSON object where the keys are in camel case inside a string in scala, and I want to convert it to snake case json (where keys are in snake case) string. Is there a clean way to do it? I was looking at Jackson object mapper and finatra object mapper but couldnt figure it out.

I can't map it to the underlying java class and then use the object mapper to retrieve a json string because the underlying class is generated by apache avro and when I try to do that object mapper throws up with exceptions, perhaps getting confused by some generated code.

2

There are 2 answers

0
oblivion On

If you want to use play-json, you can use this library. play-json-naming

0
Abdul Rahman On

So json4s seems to have what i asked for. here is what the code looks like

  import org.json4s._
  import org.json4s.jackson.JsonMethods._

  val snakeKeyJsonAST = parse(camelKeyJsonString).snakizeKeys
  val snakeKeyJsonString = compact(render(snakeKeyJsonAST))