播放2.x Json将json键转换为来自下划线的camelCase

时间:2015-03-10 04:34:45

标签: json playframework-2.2 playframework-2.3

我想将带有下划线大小写的json变换为驼峰大小写。

"{\"first_key\": \"first_value\", \"second_key\": {\"second_first_key\":\"second_first_value\"}}"

 "{\"firstKey\": \"first_value\", \"secondKey\": {\"secondFirstKey\":\"second_first_value\"}}"

这是部分代码:

val CamelCaseRegex = new Regex("(_.)")
val jsonTransformer = (__).json.update(
  //converts json camel_case field names to Scala camelCase field names  
)
val jsonRet = Json.parse(jsonStr).transform(jsonTransformer)

我在更新方法中尝试了几种方法但没有成功。

3 个答案:

答案 0 :(得分:2)

虽然只使用原生Play库来做这件事会很好,但对于Mandubian的Play Json Zipper扩展库来说,这是一个很好的用例。

这是一个快速的解决方案(没有经过详尽的测试)。首先,您需要将解析器和库添加到构建中:

resolvers += "mandubian maven bintray" at "http://dl.bintray.com/mandubian/maven"

libraryDependencies ++= Seq(
  "com.mandubian"     %% "play-json-zipper"    % "1.2"
)

然后你可以尝试这样的事情:

import play.api.libs.json._
import play.api.libs.json.extensions._

// conversion function borrowed from here:
// https://gist.github.com/sidharthkuruvila/3154845
def underscoreToCamel(name: String) = "_([a-z\\d])".r.replaceAllIn(name, {m =>
  m.group(1).toUpperCase
})

// Update the key, otherwise ignore them...
// FIXME: The None case shouldn't happen here so maybe we
// don't need it...
def underscoreToCamelCaseJs(json: JsValue) = json.updateAllKeyNodes {
  case (path, js) => JsPathExtension.hasKey(path) match {
    case Some(key) => underscoreToCamel(key) -> js
    case None => path.toJsonString -> js
  }
}

关于此输入:

val testJson = Json.obj(
  "some_str" -> JsString("foo_bar"),
  "some_obj" -> Json.obj(
    "some_field" -> Json.arr("foo", "bar")
  ),
  "an_int" -> JsNumber(1)
)

...生产:

{
  "someStr" : "foo_bar",
  "someObj" : {
    "someField" : [ "foo", "bar" ]
  },
  "anInt" : 1
}

答案 1 :(得分:2)

根据您的要求,您可以使用此库 play-json-naming 。它可以轻松地将snake_case(下划线情况)json转换为camelCase,反之亦然。 https://github.com/tototoshi/play-json-naming

答案 2 :(得分:0)

如果您使用播放> = 2.6:

final case class Blah(foo: String)

object Blah {
  import play.api.libs.json._

  implicit val config = JsonConfiguration(SnakeCase)

  implicit val blahReader:OFormat[QueueMsgEnvelope] = Json.format[Blah]
}