Play: custom Json deserialization
import ai.x.play.json.Jsonx // for >22 case class fields
val json = """{"item_id":126,"misc_id":668,"value": 10}"""
val formatter: Format[TestItem] = Jsonx.formatCaseClass[TestItem]
val reader = new Reads[TestItem] {
override def reads(json: JsValue): JsResult[TestItem] = {
json match {
case o: JsObject =>
val translated = o.fields
.map({ case (k, v) => (StringUtil.camelcase(k), v) }) // snake to camel
.map({ case (k, v) if k == "itemId" => ("id", v) case x => x }) // a custom mapping
formatter.reads(JsObject(translated)) // call the original behavior with our key transformations
case _ =>
// will never happen
formatter.reads(json)
}
}
}
Json.parse(json).as[TestItem](reader)