Select between under_score and camelCase format with json4s
Asked Answered
I

2

6

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

Instructive answered 6/8, 2014 at 19:29 Comment(0)
S
12

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)
Shult answered 16/7, 2015 at 9:25 Comment(1)
Also use snakizeKeys if you wanted to serialize back to string preserving original case: compact(Extraction.decompose(thing).snakizeKeys)Dicrotic
G
0

Currently, I think that the only option is use back ticks or Transform Function. See it at http://json4s.org/ in Extracting values section.

Best regards

Gula answered 7/8, 2014 at 13:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.