Search code examples
jsonswiftdecode

Swift: Decode json response


I have a backend response that has the format:

{
  "Items": [
    {
      "Id": "blabla",
      "Text": "blabla",
      "Description": "blabla"
    },
    {
      "Id": "blabla",
      "Text": "blabla",
      "Description": "blabla"
    }]
}

Which will be the best Swift approach to directly decode the array?

For the moment I have a struct for the response, but I have also to take in account the "Items" key, which hasn't any business logic implication for the project.

struct SearchResult: Decodable {
    
    let Id: String
    let Text: String
    let Description: String
}

Solution

  • Your JSON is missing a trailing ] on the end of the array.

    Besides that, you just need a wrapper than gives you the Items array. This, for example, works fine:

    let jsonData = """
    {
      "Items": [
        {
          "Id": "blabla",
          "Text": "blabla",
          "Description": "blabla"
        },
        {
          "Id": "blabla",
          "Text": "blabla",
          "Description": "blabla"
        }
        ]
    }
    """.data(using: .utf8)!
    
    struct ResultWrapper: Decodable {
        var Items : [SearchResult]
    }
    
    struct SearchResult: Decodable {
        
        let Id: String
        let Text: String
        let Description: String
    }
    
    do {
        let results = try JSONDecoder().decode(ResultWrapper.self, from: jsonData)
        print(results.Items) //this is your array
    } catch {
        print(error)
    }