"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?

Add a Comment

Replies

Instead of:

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

try:

let decodedResponse = try JSONDecoder().decode([Response.self], from: data)
  • thank you , it didn't work for me

Add a Comment

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)
  • It says for the decoded data"let decodedResponse = try JSONDecoder().decode(Response.self, from: data)"--> "Cannot convert value of type '(Data, URLResponse)' to expected argument type 'Data'"

  • Ok, so you need the tuple. What do you get exactly in data ?

  • I get nothing just the warning that says the given data was not valid json,

    dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around line 1, column 0." UserInfo={NSDebugDescription=Invalid value around line 1, column 0., NSJSONSerializationErrorIndex=0})))

    knowing that I am getting data from cloud function(firebase) to swiftui ? does this method work ? for example "https://us-central1-example-0f000.cloudfunctions.net/getEvent"

Add a Comment

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?:

  • I send a request in this structure for getting data on the server as I typed before 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"

            }

        }

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

    it says Error: could not handle the request in the server side and given data is not valid json on my side, this is an interpretation it might be something wrong with the method, it should be hitp pure method with specific headers I think

Add a Comment