Bhaskar Mishra
Bhaskar Mishra

Reputation: 3532

iterating over a json with json4s

I have json which has a structure like below :

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

    }
}
}

I have a case class like :

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

I want to extract the values of averagePricePerNight and starRating and return it in a List.

I am not able to get a list which includes both starRating and averagePricePerNight as within the solution array I have one more array of charges and so I dont get a List.

I used:

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

println(messagesIds.values) 

Output: List(3.5, 3.5, 3.0)

Expected Output :

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

and it gives me a list of StarRatings alone. How can I combine both and let me know if another library can do this easily.

Upvotes: 1

Views: 774

Answers (1)

mfirry
mfirry

Reputation: 3692

I'd go for something like

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)))

Note 1: starRating seems to be a Double not an Int

Note 2: your ResponseModel uses Options... but your expected seems not to.

Upvotes: 1

Related Questions