json - Play 2.x Json 将 json 键从下划线大小写转换为驼峰式大小写

标签 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)

我在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/

相关文章:

javascript - 如何将对象 JSON 转换为 d3.js 数组数据

json - 覆盖 Play JSON Combinator Writes 的值

ssl - yajsw 播放 framewok ssl 错误

java - Securesocial - 在自定义 View 中获取用户数据

playframework - 如何禁用一个数据库的进化

json - 将 R 表转换为 JSON 字符串

json - 使用 to 将大型 XML 文件转换为 JSON 以存储在 MongoDB 中

playframework - Play 框架中的请求队列

playframework - 为什么Play 2.3中的无sbt插件无法处理托管的css/less Assets ?

java - 通过测试进行热重载。玩框架怎么样?