用json4s迭代json

时间:2016-08-03 19:46:55

标签: scala json4s

我有json,其结构如下:

{
"searchResults": {
    "searchCriteria": {
        "location": {
            "originalLocation": null
        },
        "startAndEndDate": {
            "start": "2016-10-06T00:00:00",
            "end": "2016-10-09T00:00:00"
        },

        "solution": [{
                "resultID": "O1MDc1MD",
                "selected": false,
                "charges": {
                    "localCurrencyCode": "USD",
                    "averagePricePerNight": 153
                },
                "starRating": 3.5
            },

            {
                "resultID": "0MDc1MD",
                "selected": false,
                "charges": {
                    "localCurrencyCode": "USD",
                    "averagePricePerNight": 153
                },
                "starRating": 3.5
            }
        ]

    }
}
}

我有一个案例类:

case class ResponseModel(
//localCurrencyCode: Option[String],
averagePricePerNight: Option[Int],
starRating: Option[Int])

我想提取averagePricePerNight和starRating的值并将其返回到List中。

我无法获得包含starRating和averagePricePerNight的列表,因为在解决方案数组中我还有一个收费数组,所以我没有得到List。

我用过:

val messagesIds = (json \\ "solution") \ "starRating"

println(messagesIds.values) 

Output: List(3.5, 3.5, 3.0)

预期产出:

List(ResponseModel(5.0,900), ResponseModel(4.5,100), ResponseModel(4.5,1000))

它只给我一份StarRatings列表。我如何将两者结合起来,让我知道另一个库是否可以轻松完成。

1 个答案:

答案 0 :(得分:1)

我喜欢

case class Charges(localCurrencyCode: String, averagePricePerNight: Int)
case class Solution(resultID: String, selected: Boolean, charges: Charges, starRating: Double)

val parsed = (parse(json) \\ "solution").extract[List[Solution]]

val result = parsed.map(x => ResponseModel(Some(x.charges.averagePricePerNight), Some(x.starRating)))

注1:starRating似乎是Double而不是Int

注2:您的ResponseModel使用Option s ...但您的预期似乎不是。