Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select between under_score and camelCase format with json4s

How can I map a json with underscore to a camelCase field in a case class?

import org.json4s.jackson.JsonMethods.parse
import org.json4s.DefaultFormats

object Testing {
  implicit val formats = DefaultFormats.withBigDecimal

  def test = {
    val json = parse("""{"some_field":"a value"}""")
    json.extract[ThingDTO]
  }
}

case class ThingDTO(someField:String)

The error I get:

No usable value for someField Did not find value which can be converted into java.lang.String

like image 274
Neuquino Avatar asked Aug 06 '14 19:08

Neuquino


1 Answers

It doesn't seem to be documented (or at least I missed it when I was looking for it), but there is now a camelizeCase method which you can use on the parsed Json. I stumbled across it in the source code, gave it a go with some snake case Json I was working with and lo and behold, got camelised key names.

So for anyone coming across this question a year on, changing the OP's code to the following will work:

import org.json4s._
import org.json4s.DefaultFormats
import org.json4s.native.JsonMethods._

object Testing {
  implicit val formats = DefaultFormats.withBigDecimal

  def test = {
    val json = parse("""{"some_field":"a value"}""").camelizeKeys
    json.extract[ThingDTO]
  }
}

case class ThingDTO(someField:String)
like image 121
Emma Burrows Avatar answered Nov 15 '22 04:11

Emma Burrows