我想将带有下划线大小写键的 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)
我在update方法中尝试了好几种方式都没有成功。
最佳答案
虽然仅使用 native 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
}
关于json - Play 2.x Json 将 json 键从下划线大小写转换为驼峰式大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28956243/