user13154843
user13154843

Reputation:

Error in parsing through nested JSON (Swift 5)

I am trying to decode JSON but am having some difficulty with the nested values. The following image is what my JSON I'm retrieving looks like:

enter image description here

My goal is to get the 'raw' value under "regularMarketOpen", which is under "price". My structs looks like the following:

struct Response: Codable {
    let symbol: String?
    let price: [Price]?

}

struct Price: Codable {
    let quoteSourceName: String?
    let regularMarketOpen: [regularMarketOpen]?
}

struct regularMarketOpen: Codable {
    let fmt: String?
}

For whatever reason, I keep getting an error like so:

ERROR: typeMismatch(Swift.Array<Any>, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "price", intValue: nil)], debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil))

Is this an issue with my retrieval method? Thank you!

Upvotes: 0

Views: 93

Answers (1)

Tieda Wei
Tieda Wei

Reputation: 602

regularMarketOpen and price seem to be an object. But let regularMarketOpen: [regularMarketOpen]? means it's an array.

Just be careful when parse, {} is object, [] is array.

Try this:

struct Response: Codable {
    let symbol: String?
    let price: Price?
}

struct Price: Codable {
    let quoteSourceName: String?
    let regularMarketOpen: regularMarketOpen?
}

struct regularMarketOpen: Codable {
    let fmt: String?
}

To avoid these type of errors, you can use https://app.quicktype.io to generate model structs.

Happy parsing :)

Upvotes: 1

Related Questions