The given data was not valid JSON.

I am working with an API and I'm trying to pass data to a detail view but when making the call to the API it displays the error:

Detail View: dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Garbage at end." UserInfo={NSDebugDescription=Garbage at end.})))

At first, I thought my structs were wrong but I have checked them and made them retrieve the simplest information but it still doesn't work.

I'll leave my code below:

Recepie Detail Model

struct DetailResponse:Codable {
    let yields:String
    let name:String
    //let original_video_url:String?
    //let sections: [Ingredients]
    //let instructions: [Instructions]
}

/*struct Ingredients:Codable {
    let raw_text:String
}*/

struct Instructions:Codable, Identifiable {
    let id:Int
    let position:Int
    let display_text:String
    let start_time:Int
    let end_time:Int
    let temperature: String
}

class RecepieDetailModel:ObservableObject {
    //@Published var ingredients:[Ingredients] = []
    //@Published var instructions:[Instructions] = []
    //@Published var video:String? = ""
    @Published var name:String = ""

    var whichId:Int = 0

    init(whichId:Int) {
        self.whichId = whichId

        let url = URL(string: "https://tasty.p.rapidapi.com/recipes/detail?&id=\(whichId)&rapidapi-key=MY_API_KEY_GOES_HERE")!

        URLSession.shared.dataTask(with: url) { [weak self] data, _, error in

            do {
                if let recepieData = data {
                    let decodedData = try JSONDecoder().decode(DetailResponse.self, from: recepieData)
                    DispatchQueue.main.async {
                        //self?.ingredients = decodedData.sections
                        //self?.instructions = decodedData.instructions
                        //self?.video = decodedData.original_video_url
                        self?.name = decodedData.name
                    }
                }
                else {
                    print("No data")
                }
            } catch {
                print("Detail View: \(error)")
            }
        }.resume()
    }//end init()
}

Home View

struct HomeView: View {
    @ObservedObject var fetch = HomeModel()
    @State var searchText = ""
    @State var searching = false

    var body: some View {
        NavigationView {
            VStack(spacing:0) {
                SearchBar(searchText: $searchText, searching: $searching)
                List {
                    ForEach(fetch.results.filter({ (recepies: Recepies) -> Bool in

                        return recepies.name.hasPrefix(searchText) || searchText == ""
                    }), id: \.id) { recepie in
                        NavigationLink(destination: RecepieDetailView(recepie: recepie), label: {
                            Cell(recepie: recepie)
                        })
                    }
                }
                .listStyle(GroupedListStyle())
                .navigationTitle(searching ? "Searching" : "Recepies")
                .toolbar {
                    if searching {
                        Button("Cancel") {
                            searchText = ""

                            withAnimation {
                                searching = false
                                UIApplication.shared.dismissKeyboard()
                            }
                        }
                    }
                }//end toolbar
                .gesture(DragGesture()
                            .onChanged({_ in
                                UIApplication.shared.dismissKeyboard()
                            })
                )
            }//end VStack
        }//end NavigationView
    }
}

Recepie Detail View

struct RecepieDetailView: View {
    var recepie:Recepies
    @ObservedObject var details:RecepieDetailModel

    init(recepie:Recepies) {
        self.recepie = recepie
        self.details = RecepieDetailModel(whichId: recepie.id)
    }

    var body: some View {
        Image(uiImage: recepie.thumbnail_url.loadImageii())
            .resizable()
            .scaledToFit()
            .frame(height: 150)
            .cornerRadius(12)

        Text(details.name)
        /*ForEach(details.instructions, id: \.id) { instuction in
            Text(instuction.display_text)
        }*/
    }
}

The key line is:

let decodedData = try JSONDecoder().decode(DetailResponse.self, from: recepieData)

...where you try to decode a DetailResponse from json.

struct DetailResponse:Codable {
    let yields:String
    let name:String
}

If you can share some sample json (that is failing to decode), then it will be possible to comment on what might be going wrong.

The error message is accurate. In your example data, the token NULL is not valid JSON. It’s case-sensitive so it needs to be spelled as null.

I think it's worse than Scott suggests, your JSON seems to be very badly formed.
It's missing separators between items, and some of the items are ambiguous.

This works:

{
"name":"Vegan ****** Cashew Mac",
"yields":"Servings: 6"
}

Maybe you have chopped up your JSON, and posted something quite different to the original data?

The given data was not valid JSON.
 
 
Q