Click here to Skip to main content
15,868,016 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
why is this error popping out

MC] Reading from public effective user settings. Error: Couldn't decode data into Blog: 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.})))

i have this JSON

{"Response":"false","Info":[{"Estatus":"Sin Conexion"}]}


this is the sctructure of my json in swift

struct Blog: Decodable {
                let Response: String
                let articles: [Article]

                enum CodingKeys : String, CodingKey {
                    case Response

                    case articles = "Info"
                }
            }

            struct Article: Decodable {
                let Estatus: String

            }


and this is all my code

let id1 = UserDefaults.standard.string(forKey: "id1conductor")
    let id1pa = UserDefaults.standard.string(forKey: "idUser")
    if adondevaxd.text == "" || adondevaxd.text == " " || adondevaxd.text == "123" || adondevaxd.text == "abc" || adondevaxd.text == "."
    {
        self.displayAlert(title: "Usuario", message: "Debe elegir un destino")
    }


    let myURL = URL(string: "hehe")
    var request = URLRequest(url: myURL!)
    request.httpMethod = "POST"
    let posString = "ID_Conductor=\(id1!)&Destino=\(adondevaxd.text!)&ID_Pasajero=\(id1pa!)"
    request.httpBody = posString.data(using: .utf8)
    let task = URLSession.shared.dataTask(with: request) {
        data, response, error in

        if let error = error {
            print("error=\(error)")
            return
        }

        guard let data = data else {
            print("Something wrong")
            return
        }


        **// THIS SHOULD BE a valid JSON but is not i have the same in another PHP and it works** 
        struct Blog: Decodable {
            let Response: String
            let articles: [Article]

            enum CodingKeys : String, CodingKey {
                case Response

                case articles = "Info"
            }
        }

        struct Article: Decodable {
            let Estatus: String

        }

        do {
            let blog = try JSONDecoder().decode(Blog.self, from: data)


            DispatchQueue.main.async {
                if blog.Response == "true" {
                    //para ver como actua el json
                    // print(blog)
                    for article in blog.articles {

                        let tipoResponse = article.Estatus

                        if tipoResponse == "Solicitado"
                        {
                            self.displayAlert(title: "Usuario", message: "El conductor será notificado, espera la respuesta")
                            self.buttonOulet.isHidden = true
                            self.adondevaxd.isHidden = true
                            self.adondevaxd.text = ""
                            self.adondequiereirxd.isHidden = true
                            self.enviarDestino4.isHidden = true
                            self.enviarDestino3.isHidden = true
                            self.enviarDestino2.isHidden = true
                            self.enviarDestino1.isHidden = true
                            self.credencial1.isHidden = true
                            self.Credencial2.isHidden = true
                            self.Credencial3.isHidden = true
                            self.Credencial4.isHidden = true
                        }

                       else if  tipoResponse == "Ocupado" {
                            self.displayAlert(title: "Usuario", message: "El conductor ya se encuentra ocupado, selecciona otro")
                            self.map.isHidden = false
                            self.buttonOulet.isHidden = false
                            self.adondevaxd.isHidden = true
                            self.adondevaxd.text = ""
                            self.adondequiereirxd.isHidden = true
                            self.enviarDestino4.isHidden = true
                            self.enviarDestino3.isHidden = true
                            self.enviarDestino2.isHidden = true
                            self.enviarDestino1.isHidden = true
                            self.credencial1.isHidden = true
                            self.Credencial2.isHidden = true
                            self.Credencial3.isHidden = true
                            self.Credencial4.isHidden = true
                        }
                        else if  tipoResponse == "Solicitado" {
                            self.displayAlert(title: "Usuario", message: "Se envio tu solicitud al conductor, porfavor ten paciencia")
                            self.adondequiereirxd.isHidden = true
                            self.adondevaxd.isHidden = true
                            self.adondequiereirxd.isHidden = true
                        }

                            break
                }

                }
                else if  blog.Response == "false" {
                self.displayAlert(title: "Usuario", message: "No hay conexion")
                    self.map.isHidden = false
                    self.buttonOulet.isHidden = false
                    self.adondevaxd.isHidden = true
                    self.adondequiereirxd.isHidden = true
                    self.adondevaxd.text = ""
                    self.enviarDestino4.isHidden = true
                    self.enviarDestino3.isHidden = true
                    self.enviarDestino2.isHidden = true
                    self.enviarDestino1.isHidden = true
                    self.credencial1.isHidden = true
                    self.Credencial2.isHidden = true
                    self.Credencial3.isHidden = true
                    self.Credencial4.isHidden = true
                }
            }
        }
            catch {
            print("Error: Couldn't decode data into Blog:", error)

            return
        }
    }
    task.resume()

}


is my PHP wrong?

any hints? :S


<?php
require_once '../data/d.php';
error_reporting(0);
if(isset($_POST['ID_Pasajero'])){
     $Comparacion = "SELECT * FROM Solicitudes where ID_Conductor = '".$_POST['ID_Conductor']."' and Estado != '2'";
     $R = $conexion->query($Comparacion);
     $Count = mysqli_num_rows($R);
     if ($Count > 0) {
     $Comparacion = "SELECT * FROM Solicitudes where ID_Pasajero = '".$_POST['ID_Pasajero']."' and Estado != '2'";
     $R = $conexion->query($Comparacion);
     $Count = mysqli_num_rows($R);
     if ($Count > 0) {
         $Resultado = '{"Response":"true","Info":[{"Estatus":"Pendiente"}]}';
     }else{
         $Resultado = '{"Response":"true","Info":[{"Estatus":"Ocupado"}]}';
     }
     }else{
     $Comparacion = "SELECT * FROM Solicitudes where ID_Pasajero = '".$_POST['ID_Pasajero']."' and Estado != '2'";
     $R = $conexion->query($Comparacion);
     $Count = mysqli_num_rows($R);
     if ($Count > 0) {
         $Resultado = '{"Response":"true","Info":[{"Estatus":"Pendiente"}]}';
     }else{
         $sql = "INSERT INTO Solicitudes(ID_Pasajero, ID_Conductor, Destino, Estado, Estado_Calificacion) VALUES ('$_POST[ID_Pasajero]', '$_POST[ID_Conductor]', '$_POST[Destino]', '0', '0')";
         $Resultado = '{"Response":"true","Info":[{"Estatus":"Solicitado"}]}';
     }
     }
}
if ($conexion->query($Comparacion) === TRUE) {
    if ($conexion->query($sql) === TRUE) {
            echo $Resultado;
    } else {
            echo $Resultado;
    }
} else {
    if ($conexion->query($sql) === TRUE) {
            echo $Resultado;
    }
echo '{"Response":"false","Info":[{"Estatus":"Sin Conexion"}]}';
}
$conexion->close();
?>


What I have tried:

changing all code to many different ways
Posted
Updated 16-Jul-23 18:28pm
Comments
Richard MacCutchan 10-Nov-18 4:01am    
The message seems fairly clear. For some reason there appear to be extra characters after the JSON.
Bryian Tan 10-Nov-18 18:40pm    
did you verify the return is in JSON format?

1 solution

As Richard and Bryian have said, you need to look at the actual data you are processing: either use the debugger, or log it to a file for post-processing examination. Without that, you are just guessing and can't be sure what is going on.

But you have a bigger problem: Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Always use Parameterized queries instead.

When you concatenate strings, you cause problems because SQL receives commands like:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood'
The quote the user added terminates the string as far as SQL is concerned and you get problems. But it could be worse. If I come along and type this instead: "x';DROP TABLE MyTable;--" Then SQL receives a very different command:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable;--'
Which SQL sees as three separate commands:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';
A perfectly valid SELECT
SQL
DROP TABLE MyTable;
A perfectly valid "delete the table" command
SQL
--'
And everything else is a comment.
So it does: selects any matching rows, deletes the table from the DB, and ignores anything else.

So ALWAYS use parameterized queries! Or be prepared to restore your DB from backup frequently. You do take backups regularly, don't you?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900