【发布时间】:2015-06-29 17:48:45
【问题描述】:
我正在尝试遍历 JSON 并提取有关字段中对象类型的信息:
import org.json4s._
import org.json4s.JsonAST.{JArray, JString, JObject, JInt, JBool, JDouble}
import org.json4s.JsonDSL._
import org.json4s.native.JsonMethods._
def guessTypes(example: JValue): JObject = example match {
case JObject(lst) => JObject(lst.map {
case (f, JObject(nested)) => JField(f, ("type" -> "object") ~ ("properties" -> guessTypes(nested)))
case (f, JString(s)) => JField(f, "type" -> "string")
case (f, JInt(num)) => JField(f, "type" -> "integer")
case (f, JDouble(double)) => JField(f, "type" -> "double")
case (f, JBool(b)) => JField(f, "type" -> "bool")
case (f, JArray(jarray: List[JInt])) => JField(f, ("type" -> "array") ~ ("items" -> "integer"))
case (f, JArray(jarray: List[JString])) => JField(f, ("type" -> "array") ~ ("items" -> "string"))
case (f, JArray(jarray: List[JObject])) => JField(f, ("type" -> "array") ~ ("items" -> "object")) ~ ("properties" -> jarray.map{ x => guessTypes(x)}))
})}
如果发生:
def example = """
|{
| "partners_data": [
| {
| "info": {
| "label": "partner45"
| },
| "partner_id": "partner45",
| "data": {
| "field": 24
| }
| }
| ],
| "name": "*****(",
| "location": [
| 1,
| 2
| ],
| "is_mapped": false
|}
""".stripMargin
得到结果:
{"data":{"type":"array","items":"object"},"name":{"type":"string"},"location":{"type":"数组","items":"object"},"is_mapped":{"type":"bool"}}
这不是合适的结果,因为对于“位置”中的关键“项目”,预期值为“整数”。
看起来 Scala 无法区分 JArrays 中除了 JValue 之外的任何其他内容。如果我替换
case (f, JArray(jarray: List[JInt]))
通过最后一个字符串,对于“location”中的key“items”,会得到“object”的值,但是对于其他字段的值会是错误的。
我怎样才能绕过 scala 模式匹配和 json4s 框架的这种特殊性?
【问题讨论】:
-
你用的是什么版本的Json4s?使用
"org.json4s" %% "json4s-native" % "3.2.2"时,我得到了正确的类型。 -
我正在使用
"org.json4s" %% "json4s-native" % "3.2.11"。在我们的例子中,没有机会使用早期版本的 json4s。
标签: scala scala-2.10 json4s