从Scala中的复杂对象反序列化JSON字段

时间:2018-10-13 00:55:56

标签: json scala serialization gson deserialization

我正在使用Scala编程语言

我格式化的json负载是

{
   "took":1,
   "timed_out":false,
   "_shards":{
      "total":25,
      "successful":25,
      "failed":0
   },
   "hits":{
      "total":1,
      "max_score":0.72271335,
      "hits":[
         {
            "_index":"machinename_guid",
            "_type":"type",
            "_id":"id",
            "_score":0.72271335,
            "_source":{
               "Name":"NAME",
               "Data":{
                  "Name":"NAME"
                  "Ver":"VERSION",
                  "$type":"lib, ServiceTest",
                  "ProductName":"PRODUCTNAME",
                  "Id":"ID"
                  "Data":"DATA TOBE RETRIVED"
               }
            }
         }
      ]
   }
}

我想将以下部分反序列化为类

 "Data":{
    "Name":"NAME"
    "Ver":"VERSION",
    "$type":"lib, ServiceTest",
    "ProductName":"PRODUCTNAME",
    "Id":"ID"
    "Data":"DATA TOBE RETRIVED"
 }

在Scala中实现此目标的最简单方法是什么?

1 个答案:

答案 0 :(得分:0)

最简单的选择之一是反序列化对类的完整Json响应,并从该类中提取所需的数据。

case class Data(name: String,ver: String,type: String,productName: String,id: String,data: String)
case class Foo(name: String,data: Data)
case class Result(_source: Foo, _score: Float, _index: String, _type: String, _id: String)
case class HitsResult(hits: List[Result], total: Int)
case class Response(hits: HitsResult)

现在,您可以使用任何JSON库对上述Response案例类反序列化Json响应,并且可以轻松地从响应中提取所需数据,即Foo。