给出一个带有嵌套对象的JSON对象,该对象的属性是未知的:
{ "Key":"01234",
"eventProperties":{
"unknownProperty1":"value",
"unknownProperty2":"value",
"unknownProperty3":"value"
},
}
我尝试使用json4s的提取函数和以下案例类(在Scala中):
case class nestedClass(Key:String, eventProperties:Map[(String,Any)])
导致以下错误:
org.json4s.package$MappingException: Can't find constructor for nestedClass
是否可以在不定义eventProperties的所有可能属性的情况下执行此操作?
更新: json4s 3.2.10中存在导致此问题的错误 - 更新到3.2.11并解压缩到Map [String,Any]工作正常。
答案 0 :(得分:2)
我不确定您为了获得发布的例外而做了什么,但以下工作(请注意Map
而不是List
):
import org.json4s._
import org.json4s.jackson.JsonMethods._
import org.json4s.DefaultFormats
val json = parse("""
{ "key":"01234",
"eventProperties":{
"unknownProperty1":"value",
"unknownProperty2":"value",
"unknownProperty3":"value"
}
}
""")
case class NestedClass(key:String, eventProperties:Map[String,Any])
implicit val formats = DefaultFormats
json.extract[NestedClass]
答案 1 :(得分:0)
为了将eventProperties作为List [(String,Any)],你的json应该是,
""" {
"key": "01234",
"eventProperties": [
{"unknownProperty1": "value"},
{"unknownProperty2": "value"},
{"unknownProperty3": "value"}
]
}"""
否则,您可以使用Map而不是List作为
case class nestedClass1(key:String, eventProperties:Map[String,Any])
然后转换为nestedClass为nestedClass( n1.key, n1.eventProperties.toList)