2
votes

I have a sample JSON where its just an array of strings and has no keys and would like to use the Decodable protocol to consume the JSON and create a simple model out of it.

The json looks like this:

{ "names": [ "Bob", "Alice", "Sarah"] }

Just a collection of strings in an simple array.

What I'm unsure about is how do I use the new Swift Decodable protocol to read this into a model without a key.

Most of the examples I've seen assume the JSON has a key.

IE:

// code from: Medium article: https://medium.com/@nimjea/json-parsing-in-swift-2498099b78f

struct User: Codable{
       var userId: Int
       var id: Int
       var title: String
       var completed: Bool
}

do {
    //here dataResponse received from a network request
    let decoder = JSONDecoder()
    let model = try decoder.decode([User].self, from:
                 dataResponse) //Decode JSON Response Data 
    print(model)
} catch let parsingError {
    print("Error", parsingError)
}

This above example assumes that the json is a key-value; how can I use the decodable protocol to de-code the JSON without keys?

With thanks

2
It's important to note your current user model has no relation to the current jsonSh_Khan
"Most of the examples I've seen assume the JSON has a key." Your JSON does have a key.matt
I apologise, I perhaps missed that onezardon

2 Answers

3
votes

The corresponding struct of this JSON is

struct User: Decodable {
   let names: [String]
}

and decode

let model = try decoder.decode(User.self, from: dataResponse)

and get the names with

let names = model.names

or traditionally without the overhead of JSONDecoder

let model = try JSONSerialization.jsonObject(with: dataResponse) as? [String:[String]]
3
votes

For this simple structure of json , i guess it's better not to create any structs and use

let model = try decoder.decode([String:[String]].self, from: dataResponse)
print(model["names"])

the json fiting for your model is

{

    "names": [{ 
          "userId": 2,
         "id": 23,
         "title": "gdgg",
         "completed": true

    }]
}


struct Root: Codable {
    let names: [User]
}

struct User: Codable {
    let userId, id: Int
    let title: String
    let completed: Bool

}