Sanoj Kashyap
Sanoj Kashyap

Reputation: 5060

Parse Nested Object using Object Mapper in Swift 4

I have JSON response like below

{
    "XYZ": {
        "ABC": {
            "PQR": [
                {
                    "details": {
                        "date":1221,
                        "number": 30
                    }
                }
            ]
        }
    }
}

I want to fetch the details of "date" and "number" directly. without parsing separately XYZ, ABC,PQR AND details.

struct Trial: Mappable {
    var PQR!
    init() {}
    init?(map: Map) {}

    mutating func mapping(map: Map) {
        trialPeriod <- map["XYZ.ABC.PQR"]    
    }
}

I am to parse till PQR. After that, I am not able to parse. Could you please let me know how to get "details" after parsing till PQR??

OR

Let me know how to get the parse directly to a number? I tried many times but could not able to do so.

Upvotes: 0

Views: 659

Answers (1)

user9335240
user9335240

Reputation: 1789

You couldn't parse nested after the PQR just because it is a JSON Array not a JSON Object. So, you can do something like that if you are sure that it is the first element of the array only.

struct Trial: Mappable {
    var PQR!
    init() {}
    init?(map: Map) {}

    mutating func mapping(map: Map) {
        trialPeriod <- map["XYZ.ABC.PQR.0.details.date"]
    }
}

Notice the .0, it means the first item in the array.

Or, the better, is trying to parse XYZ.ABC.PQR as an array, then parse individual items in it

Upvotes: 2

Related Questions