[英]how to represent nested JSON object in a case class using Json4s?
Given an example JSON object with a nested object who's properties are unkown: 给定一个带有嵌套对象的JSON对象示例,该对象的属性是未知的:
{ "Key":"01234",
"eventProperties":{
"unknownProperty1":"value",
"unknownProperty2":"value",
"unknownProperty3":"value"
},
}
I have tried to use json4s' extract function with the following case class (In Scala): 我尝试将json4s的提取函数与以下案例类(在Scala中)一起使用:
case class nestedClass(Key:String, eventProperties:Map[(String,Any)])
Which results in the following error: 导致以下错误:
org.json4s.package$MappingException: Can't find constructor for nestedClass
Is it possible to do this without defining every possible property of eventProperties? 是否可以在未定义eventProperties的每个可能属性的情况下执行此操作?
Update: there was a bug in json4s 3.2.10 causing this issue - updating to 3.2.11 and extracting to Map[String,Any] works fine. 更新: json4s 3.2.10中存在一个错误导致此问题-更新至3.2.11并提取到Map [String,Any]可以正常工作。
I'm not sure what you are doing to get the exception you have posted, but the following works (note a Map
instead of List
): 我不确定要怎么做才能获取已发布的异常,但是可以进行以下工作(注意使用
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]
In Order to get eventProperties as List[(String, Any)], your json should be, 为了获取eventProperties作为List [(String,Any)],您的json应该是,
""" {
"key": "01234",
"eventProperties": [
{"unknownProperty1": "value"},
{"unknownProperty2": "value"},
{"unknownProperty3": "value"}
]
}"""
Otherwise, you can use Map instead of List as case class nestedClass1(key:String, eventProperties:Map[String,Any])
and then convert to nestedClass as nestedClass( n1.key, n1.eventProperties.toList)
否则,您可以使用Map而不是List作为
case class nestedClass1(key:String, eventProperties:Map[String,Any])
,然后将其转换为nestedClass作为nestedClass( n1.key, n1.eventProperties.toList)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.