C.Jones
C.Jones

Reputation: 161

Parsing Json object within a Json Object Swift 5

I'm trying to parse some json in Xcode that is basically a bunch of objects in an object. The json looks like this below.

{"TDOC": {
"assetType": "EQUITY",
"assetMainType": "EQUITY",
"cusip": "87918A105",
"symbol": "TDOC"}}

I am parsing it using the code below in Xcode using swift5

do {            
   if let json = try JSONSerialization.jsonObject(with: jData, options: []) as? [String: Any] {
      if let pr = json["TDOC"] as? Array<Dictionary<String, Any>> {
         for p in pr {
             print(p["assetType"] ?? "")
         }
      }
   }
} catch let err {
   print(err.localizedDescription)
}

I'm trying to get the assetType value but when I run the code, nothing prints out to the console. When I debug, it seems like Xcode just skips right over my for in loop for that prints the assetType for some reason. Any help on this is appreciated.

Upvotes: 2

Views: 3088

Answers (3)

Sanad Barjawi
Sanad Barjawi

Reputation: 578

1. Make a reflecting class of your data and make it conform to Codable protocol

    import Foundation

    // MARK: - Welcome
    struct MyObject: Codable {
        let tdoc: Tdoc

        enum CodingKeys: String, CodingKey {
            case tdoc = "TDOC"
        }
    }

    // MARK: - Tdoc
    struct Tdoc: Codable {
        let assetType, assetMainType, cusip, symbol: String
    }

1. Parse it using JSONDecoder:

    do {

           let myObject = try JSONDecoder().decode(MyObject.self, from: jsonData)
           print(myObject.tdoc.assetType)

    } catch {
           print(error)
    }

heres an apple doc for a broader info about Encoding, Decoding and CodingKeys protocols

https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types

Hope this helps :)

Upvotes: 0

HardikS
HardikS

Reputation: 714

You can't treat TDOC object as an Array. As it is a dictionary object, you can take it as Dictionary directly.

You can do it like this.

do {

    if let json = try JSONSerialization.jsonObject(with: jData, options: []) as? [String: Any] {

        if let pr = json["TDOC"] as? Dictionary<String, Any> {
            print(pr["assetType"])
        }
    }

} catch let err {

    print(err.localizedDescription)
}

Upvotes: 3

sudhanshu-shishodia
sudhanshu-shishodia

Reputation: 1108

Try this.

"TDOC" key corresponds to a dictionary value, not an array. No for loop needed as well.

do {

    if let json = try JSONSerialization.jsonObject(with: jData, options: []) as? [String: Any] {

        if let pr = json["TDOC"] as? [String: Any] {

                print(pr["assetType"])
        }
    }

} catch let err {

    print(err.localizedDescription)
}

Hope this helps.

Upvotes: 0

Related Questions