"The given data was not valid JSON."

I have this data

{
"data":{
"date":"07-03-2022",
"type":"airplane" 
}
}

and my code is

struct JsonResult: View{

    enum LoadingState {

           case idle, loading, loaded(UserData), failure(Error)

       }

@State private var state : LoadingState = .idle

 

 var body: some View {

     VStack {

         switch state {

             case .idle: EmptyView()

             case .loading: ProgressView()

             case .loaded(let userData):

                 

                 VStack(alignment: .leading) {

                     Text(userData.date)

                         .font(.headline)

                     Text(userData.type)

                         .font(.headline)

                 }

                 

             case .failure(let error): Text(error.localizedDescription)

         }

     }.task {

         await loadData()

     }

 }

    struct Response: Encodable, Decodable {

        var data: UserData

    }



    struct UserData: Codable {

        var date: String

        var type: String

        private enum CodingKeys: String, CodingKey {

            case date = "date"

            case type = "type"

        }

    }

    

 

 func loadData() async {

     

     state = .loading

     guard let url = URL(string: "MyUrl(related to cloud functions") else {

         state = .failure(URLError(.badURL))

         return

     }

     do {

         let (data,_) = try await URLSession.shared.data(from: url)

         // more code

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

         state = .loaded(decodedResponse.data)

         

     } catch {

         state = .failure(error)

         print(error) // this shows the real DecodingError

     }

 }

}

and after all this work, i want to get data from cloud functions, I got the same error, "The given data was not valid JSON.", although the data structure is valid json but It says data was not valid json ! any solution ? Thank you alot

Can you print a UTF8 representation of the data?

Instead of:

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

try:

let decodedResponse = try JSONDecoder().decode([Response.self], from: data)

What do you expect in the second element of tuple ?

         let (data,_) = try await URLSession.shared.data(from: url)

Would this work ?

         let data = try await URLSession.shared.data(from: url)

If you're seeing this as well then the exception thrown is correct, do you need to pass auth headers to the server assuming the access point is not a public endpoint?:

"The given data was not valid JSON."
 
 
Q