Reputation: 161
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
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
Hope this helps :)
Upvotes: 0
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
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