ward
ward

Reputation: 77

Swift 4 json decode with top level array

While getting JSON data from my API, I can't get it to decode properly.

[ 
{ 
"success": "true",
 "message": "testtt" 
} 
]

This is what my API output looks like.

As we can see, my PHP outputs the values as an top level array.

How can I read out this information in Swift 4?

let json = try JSONDecoder().decode([API].self, from: data)

returns:

success: "true", message: "testtt"

This is what the struct looks like:

struct API: Decodable{
    let success: String
    let message: String

    init(jsont: [String: Any]){
        success = jsont["success"] as? String ?? ""
        message = jsont["message"] as? String ?? ""
    }
}

But then I don't know how to read out this data further.

Any ideas?

Upvotes: 0

Views: 2121

Answers (2)

Leo Dabus
Leo Dabus

Reputation: 236360

There is no need to creat a custom initialiser. You just use the Array type [API].self when decoding your json:

struct API: Decodable{
    let success: String
    let message: String
}

let dataJSON = Data("""
[
    {
        "success": "true",
        "message": "testtt"
    }
]
""".utf8)

do {
    if let result = try JSONDecoder().decode([API].self, from: dataJSON).first {
        print(result.success)
        print(result.message)
    }
} catch {
    print(error)
}

Upvotes: 4

JamesVoo
JamesVoo

Reputation: 171

If you want to access make one more struct like

struct data: Decodable{
let API: [API]
}

Then in your program you must decode like below above

let json = try JSONDecoder().decode(data.self, from: data)

and access to them

data.API[i].success
data.API[i].message

Upvotes: -2

Related Questions