简体   繁体   中英

Parse a dynamically named json object in Scala

how can I parse this kind of json with spray-json? How does the guid object go into a case class or do I need to write some kind of custom reader?

{
    "referredEntities":{
        "012e2ec1-c205-4657-81d7-1e06eac1a849":{
            "typeName":"type1",
            "attributes":{
                "owner":"dave",
                "qualifiedName":"test",
                "name":"test"...

Assuming that your JSON object will be something similar to this:

{
    "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"
        }
     }}
}

Consider the following solution:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM