我怎么能用spray-json解析这种json? guid对象如何进入案例类或者我是否需要编写某种自定义阅读器?
{
"referredEntities":{
"012e2ec1-c205-4657-81d7-1e06eac1a849":{
"typeName":"type1",
"attributes":{
"owner":"dave",
"qualifiedName":"test",
"name":"test"...
答案 0 :(得分:0)
假设您的JSON对象与此类似:
{
"referredEntities": {
"012e2ec1-c205-4657-81d7-1e06eac1a849":{
"typeName":"type1",
"attributes":{
"owner":"dave",
"qualifiedName":"test",
"name":"test"
}
},
"012e2ec1-c205-4657-81d7-1e06ea1234":{
"typeName":"type2",
"attributes":{
"owner":"nicky",
"qualifiedName":"test1",
"name":"test22"
}
}}
}
考虑以下解决方案:
import spray.json._
val source = """{
| "referredEntities":{
| "012e2ec1-c205-4657-81d7-1e06eac1a849":{
| "typeName":"type1",
| "attributes":{
| "owner":"dave",
| "qualifiedName":"test",
| "name":"test"
| }
| },
| "012e2ec1-c205-4657-81d7-1e06ea1234":{
| "typeName":"type1",
| "attributes":{
| "owner":"dave",
| "qualifiedName":"test",
| "name":"test"
| }
| }}}""".stripMargin
val jsonAst = source.parseJson
case class Attributes(owner: String, qualifiedName: String, name: String)
case class Entity(typeName: String, attributes: Attributes)
case class ReferredEntity(entityUUID: String, entity: Entity)
case class Source(referredEntities: Seq[ReferredEntity])
object MyJsonProtocol extends DefaultJsonProtocol {
implicit val attributesFmt = jsonFormat3(Attributes)
implicit val entityFmt = jsonFormat2(Entity)
implicit object SourceJsonFormat extends RootJsonReader[Source] {
def read(value: JsValue) = value.asJsObject.getFields("referredEntities") match {
case Seq(obj: JsObject) => Source(obj.fields.toSeq.map(item => ReferredEntity(item._1, entityFmt.read(item._2))))
}
}
}
import MyJsonProtocol._
SourceJsonFormat.read(jsonAst)