scala-如何将JSON字符串解析为单独的记录?

时间:2018-08-07 12:07:40

标签: json scala json4s

我写了一种连接JSON值的方法。

def mergeSales(storeJValue: JValue): String = {
    val salesJValue: JValue = parse(rawJson)

    val store = compact(render(storeJValue))
    val sales = compact(render(salesJValue))
    val mergedSales: String = s"""{"store":$store,"sales":$sales}"""

    mergedSales
  }

结果,我得到了这样的字符串,即一个具有一系列相应销售的商店:

{"store":{"store_id":"01","name":"Store_1"}, "sales":[{"saleId": 10, "name": "New name1", "saleType": "New Type1"}, {"saleId": 20, "name": "Some name1", "saleType": "SomeType5"}, {"saleId": 30, "name": "Some name3", "saleType": "SomeType3"}]}  

我应该如何解析它以获取记录列表,在该记录中同一商店从数组映射到每个销售?我希望它看起来像这样:

  {"store":{"store_id":"01","name":"Store_1"}, "sale":{"saleId": 10, "name": "New name1", "saleType": "New Type1"}}
  {"store":{"store_id":"01","name":"Store_1"}, "sale":{"saleId": 20, "name": "New name2", "saleType": "New Type2"}}
  {"store":{"store_id":"01","name":"Store_1"}, "sale":{"saleId": 30, "name": "Some name3", "saleType": "SomeType3"}}

实际上,销售中有大量字段,因此创建案例类将非常复杂。

1 个答案:

答案 0 :(得分:1)

我认为使用json4s API的最佳方法是提取所有json代码并将其转换为地图,而不是您可以轻松遍历

您需要创建案例类:

case class Store(store_id: String, name: String)

case class Sale(saleId:String, name:String, saleType:String)

case class Result(store: Store, sale: Sale)

case class SaleStore(store: Store, sales: List[Sale])

然后很直接地使用json4s获得解决方案

val str =
      """{
        |  "store": {
        |    "store_id": "01",
        |    "name": "Store_1"
        |  },
        |  "sales": [
        |    {
        |      "saleId": 10,
        |      "name": "New name1",
        |      "saleType": "New Type1"
        |    },
        |    {
        |      "saleId": 20,
        |      "name": "Some name1",
        |      "saleType": "SomeType5"
        |    },
        |    {
        |      "saleId": 30,
        |      "name": "Some name3",
        |      "saleType": "SomeType3"
        |    }
        |  ]
        |}""".stripMargin

import org.json4s._
import org.json4s.jackson.JsonMethods._
implicit val formats = org.json4s.DefaultFormats
val saleStore = parse(str).extract[SaleStore]
val result = saleStore.sales.flatMap(sale => List(saleStore.store -> sale))

val mapper: ObjectMapper = new ObjectMapper()
mapper.registerModule(DefaultScalaModule)

result.map(r => mapper.writeValueAsString(Result(r._1, r._2))).foreach(println)

输出:

{"store":{"store_id":"01","name":"Store_1"},"sale":{"saleId":"10","name":"New name1","saleType":"New Type1"}}
{"store":{"store_id":"01","name":"Store_1"},"sale":{"saleId":"20","name":"Some name1","saleType":"SomeType5"}}
{"store":{"store_id":"01","name":"Store_1"},"sale":{"saleId":"30","name":"Some name3","saleType":"SomeType3"}}