The given data was not valid JSON Garbage at end









up vote
-2
down vote

favorite












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();
?>









share|improve this question

















  • 1




    Possible duplicate of How to create an array for JSON using PHP?
    – miken32
    Nov 9 at 23:56






  • 1




    in the last if/else blocks there is the possiblity to send two json strings. I suppose you're simply missing an extra else to wrap the last echo '


    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();
    ?>









    share|improve this question

















    • 1




      Possible duplicate of How to create an array for JSON using PHP?
      – miken32
      Nov 9 at 23:56






    • 1




      in the last if/else blocks there is the possiblity to send two json strings. I suppose you're simply missing an extra else to wrap the last echo '


      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();
      ?>









      share|improve this question













      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();
      ?>






      php json swift4






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 9 at 23:50









      José Raúl

      15




      15







      • 1




        Possible duplicate of How to create an array for JSON using PHP?
        – miken32
        Nov 9 at 23:56






      • 1




        in the last if/else blocks there is the possiblity to send two json strings. I suppose you're simply missing an extra else to wrap the last echo '{"Response.....
        – Jeff
        Nov 9 at 23:57











      • If you want to return JSON, use the appropriate tools to create it. Also get rid of ?> at the end of your PHP (it can cause whitespace to be sent after your content) and send the correct Content-Type header for JSON.
        – miken32
        Nov 9 at 23:58













      • 1




        Possible duplicate of How to create an array for JSON using PHP?
        – miken32
        Nov 9 at 23:56






      • 1




        in the last if/else blocks there is the possiblity to send two json strings. I suppose you're simply missing an extra else to wrap the last echo '{"Response.....
        – Jeff
        Nov 9 at 23:57











      • If you want to return JSON, use the appropriate tools to create it. Also get rid of ?> at the end of your PHP (it can cause whitespace to be sent after your content) and send the correct Content-Type header for JSON.
        – miken32
        Nov 9 at 23:58








      1




      1




      Possible duplicate of How to create an array for JSON using PHP?
      – miken32
      Nov 9 at 23:56




      Possible duplicate of How to create an array for JSON using PHP?
      – miken32
      Nov 9 at 23:56




      1




      1




      in the last if/else blocks there is the possiblity to send two json strings. I suppose you're simply missing an extra else to wrap the last echo '{"Response.....
      – Jeff
      Nov 9 at 23:57





      in the last if/else blocks there is the possiblity to send two json strings. I suppose you're simply missing an extra else to wrap the last echo '{"Response.....
      – Jeff
      Nov 9 at 23:57













      If you want to return JSON, use the appropriate tools to create it. Also get rid of ?> at the end of your PHP (it can cause whitespace to be sent after your content) and send the correct Content-Type header for JSON.
      – miken32
      Nov 9 at 23:58





      If you want to return JSON, use the appropriate tools to create it. Also get rid of ?> at the end of your PHP (it can cause whitespace to be sent after your content) and send the correct Content-Type header for JSON.
      – miken32
      Nov 9 at 23:58


















      active

      oldest

      votes











      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













       

      draft saved


      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53234711%2fthe-given-data-was-not-valid-json-garbage-at-end%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown






























      active

      oldest

      votes













      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes















       

      draft saved


      draft discarded















































       


      draft saved


      draft discarded














      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53234711%2fthe-given-data-was-not-valid-json-garbage-at-end%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown





















































      Required, but never shown














      Required, but never shown












      Required, but never shown







      Required, but never shown

































      Required, but never shown














      Required, but never shown












      Required, but never shown







      Required, but never shown







Popular posts from this blog

Use pre created SQLite database for Android project in kotlin

Darth Vader #20

Ondo