如何使用 Json4s 在案例 class 中表示嵌套的 JSON 对象?
how to represent nested JSON object in a case class using Json4s?
给出一个示例 JSON 具有嵌套对象的对象,其属性未知:
{ "Key":"01234",
"eventProperties":{
"unknownProperty1":"value",
"unknownProperty2":"value",
"unknownProperty3":"value"
},
}
我尝试在以下情况下使用 json4s 的提取函数 class(在 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] 工作正常。
我不确定你在做什么来获得你发布的异常,但以下是有效的(注意 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]
为了将 eventProperties 获取为列表[(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)
给出一个示例 JSON 具有嵌套对象的对象,其属性未知:
{ "Key":"01234",
"eventProperties":{
"unknownProperty1":"value",
"unknownProperty2":"value",
"unknownProperty3":"value"
},
}
我尝试在以下情况下使用 json4s 的提取函数 class(在 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] 工作正常。
我不确定你在做什么来获得你发布的异常,但以下是有效的(注意 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]
为了将 eventProperties 获取为列表[(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)