Search code examples
jsonswiftswiftuiget

SwiftUI - Error Received When Making Get Request


I am receiving the following error when executing a JSON get request:

Thread 6: Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "id", intValue: nil)], debugDescription: "Expected to decode String but found a number instead.", underlyingError: nil))

Here is the code I am using that makes the fetch request:

struct Get: Codable, Identifiable {
var id = UUID()
var title: String
var body: String
//var meals: [[String: String?]]
//var strInstructions: String

}

class Api {
func getData(completion: @escaping ([Get]) -> ()) {
    guard let url = URL(string: "https://jsonplaceholder.typicode.com/posts") else {return}
    
    URLSession.shared.dataTask(with: url) { (data, _, _) in
        let get = try! JSONDecoder().decode([Get].self, from: data!) //The error appears on this line - the ".decode" gets underlined as the source of the error
        
        DispatchQueue.main.async {
            completion(get)
        }
    }
    .resume()
}

Lastly, here is the demo view I set up as a test to display the data:

struct apitestview: View {

@State var getRecipe: [Get] = []

var body: some View {
    List(getRecipe) { get in
        Text(get.body)
        
    }
    .onAppear() {
        Api().getData { (get) in
            self.getRecipe = get
        }
    }
}

Any thoughts? I have tried a few different variants of the code above, but I cannot seem to get to the bottom of the error.

Edits:

Here is a piece of the JSON data

[
{
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
},
{
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
}

]


Solution

  • The fix was to add the missing pieces returned in the JSON object to my data model. See below:

    struct Get: Codable, Identifiable {
    var userId: Int //newly added
    var id: Int //newly added
    var title: String
    var body: String