Spray-json将json的一部分转换为Map [String,List [Double]]

时间:2014-11-17 20:26:57

标签: json scala spray spray-json

我有以下json

   {  
       "op":{  
          "samples":{  
             "ep_mem_high_wat":[  0,0,0,0,0,0,0],
             "ep_mem_low_wat":[  0,0,0,0,0,0,0]
          },
          "samplesCount":60,
          "isPersistent":true,
          "lastTStamp":1415619627689,
          "interval":1000
       },
       "hot_keys":[  
          {  
             "name":"counter::F03E91E2A4B9C25F",
             "ops":0.11010372549516878
          }
       ]
    }

我想将这个Json的“samples”属性解析为Map [String,List [Double]] as

Map[String,List[Double]]("ep_mem_high_wat" -> [ 0,0,0,0,0,0,0],"ep_mem_low_wat" -> [0,0,0,0,0,0,0])

为此我执行以下操作:我创建我的案例类

  case class Samples(properties:Map[String,List[Double]])
  case class Op(samples:Samples,samplesCount:Int,isPersistent:Boolean,lastTStamp:Long,interval:Int)
  case class Key(name:String,ops:Double)
  case class BucketStatisticResponse(op:Op,hot_keys:List[Key])

然后我创建自定义Json协议

 object BucketStatisticJsonProtocol extends DefaultJsonProtocol {

    implicit object SamplesJsonFormat extends RootJsonFormat[Samples] {

      def write(obj: Samples) = obj.toJson
      def read(value: JsValue) =  {
         val props = value.asJsObject.fields
          Samples(value.convertTo[Map[String,List[Double]]])
      }
    }
    implicit val keyFormat = jsonFormat2(Key)
    implicit val opFormat = jsonFormat5(Op)
    implicit val bucketStatisticFormat= jsonFormat2(BucketStatisticResponse)
  }

然后我正在尝试解析json

 import BucketStatisticJsonProtocol._
 val res =  json.toJson.convertTo[BucketStatisticResponse]

结果我得到了以下例外:

Exception in thread "main" spray.json.DeserializationException: Object expected in field 'op'
    at spray.json.package$.deserializationError(package.scala:23)
    at spray.json.ProductFormats$class.fromField(ProductFormats.scala:54)
    at high.availability.poc.DynamicJson$BucketStatisticJsonProtocol$.fromField(DynamicJson.scala:23)

我做错了什么?

1 个答案:

答案 0 :(得分:3)

查看错误消息:它抱怨它在op字段的AST中找到的值的类型。因此,您实际解析的文档可能与上面的示例不匹配。

除此之外,你的代码看起来还不错。就像品味一样,我通常不会延伸DefaultJsonProtocol;我将JSON格式放在包对象中,并import DefaultJsonProtocol._根据需要处理任何简单的转换。