0

Background: I'm using swift [email protected] and I need to parse json data

AF.request("https://xxx.json").validate().responseDecodable(of: Decodable)

The data looks like:

[
   [
       "a",
       123,
       1.0,
   ],
   [
       "b",
       456,
       2.0,
   ],
]

My code (this is the wrong way):

struct Item: Codable {
   var name: String
}

...responseDecodable(of: [Item].self)

Should I use enum instead? I read some similar answers but they all have keys at some point, my data is pure array without keys.

2
  • 2
    This is extremely unpractical JSON. Basically you can decode nested arrays directly without creating structs, but the inner array must be homogenous (one type). Yours is not, so you have to create a struct, decode the array as (nested)unkeyedContainer and determine the different types manually. Commented Oct 7, 2022 at 10:30
  • @vadian thanks, I will change the json structure. I'm new to swift, for now I'm curious about how to did. Commented Oct 7, 2022 at 10:39

1 Answer 1

1

Assuming the types are always the same in the same order this is a simple example how to decode the inner array, the struct member names are arbitrary

struct Item: Decodable {
    let name: String
    let someInt: Int
    let someDouble: Double
    
    init(from decoder: Decoder) throws {
        var container = try decoder.unkeyedContainer()
        name = try container.decode(String.self)
        someInt = try container.decode(Int.self)
        someDouble = try container.decode(Double.self)
    }
}

and decode [Item].self

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.