Member 14024497 Ответов: 0

Как получить JSON-данные, если они разделены ", "


Привет программистам, у меня была такая проблема.

это мой Json
echo '{  
         "ID":"'.$row[0].'",  
           
         "Nombre":"'.$row[3].'",  
         "Matricula":"'.$row[7].'",  
         "Vehiculo":"'.$row[8].'",  
         "Modelo":"'.$row[9].'",  
         "Identificacion":"'.$row[10].'",  
         "Distancia":"'.$Distancia.'",  
         },';  


это данные из "драйвер в моем приложении" Json будет автоматически увеличиваться каждый раз, когда "драйвер" входит в систему, и это будет выглядеть так, когда получает вызов с PHP

echo '{  
         "ID":"'.$row[0].'",  
           
         "Nombre":"'.$row[3].'",  
         "Matricula":"'.$row[7].'",  
         "Vehiculo":"'.$row[8].'",  
         "Modelo":"'.$row[9].'",  
         "Identificacion":"'.$row[10].'",  
         "Distancia":"'.$Distancia.'",  
         },';   // as you can see it is separeted with a ','

         "ID":"'.$row[0].'",  
           
         "Nombre":"'.$row[3].'",  
         "Matricula":"'.$row[7].'",  
         "Vehiculo":"'.$row[8].'",  
         "Modelo":"'.$row[9].'",  
         "Identificacion":"'.$row[10].'",  
         "Distancia":"'.$Distancia.'",  
         },'; 



Итак, я хочу знать, как разделять в swift (не меняя код в php, если в этом нет необходимости)

func iamarjson()
    {
     
        
        let myURL = URL(string: "he he (michael jackson") 
        var request = URLRequest(url: myURL!) 
        request.httpMethod = "POST"
        let posString = "Client_lat=\(coordLat.text!)&Client_lon=\(coordLong.text!)" 
        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 is my Json 
            struct Blog: Decodable {
                let Response: String
                let articles: [Article]
            
                
                enum CodingKeys : String, CodingKey {
                    case Response
                    
                    case articles = "Perfil"
                }
            }
           
            struct Article: Decodable {
                let ID: String
                let Foto: String
                let Nombre: String
                let Matricula: String
                let Vehiculo: String
                let Modelo: String
                let Identificacion: String
                let Distancia: String
         // as you can see, is a structure for 1 json data, but it will be displayed with a ',' if theres more than 1 "driver"
            }
            
            
            
            do {
                
                
                let blog = try JSONDecoder().decode(Blog.self, from: data)
                
               
                DispatchQueue.main.async {
                    if blog.Response == "true" {
                        
                        for article in blog.articles {
                            let id = article.ID
                            UserDefaults.standard.set(id, forKey: "idJson")
                            let foto = article.Foto
                            UserDefaults.standard.set(foto, forKey: "fotoJson")
                            let nombre = article.Nombre
                            UserDefaults.standard.set(nombre, forKey: "nombreJson")
                            let matricula = article.Matricula
                            UserDefaults.standard.set(matricula, forKey: "matriJson")
                            let vehiculo = article.Vehiculo
                            UserDefaults.standard.set(vehiculo, forKey: "vehiJson")
                            let modelo = article.Modelo
                            UserDefaults.standard.set(modelo, forKey: "modeloJson")
                            let identificacion = article.Identificacion
                            UserDefaults.standard.set(identificacion, forKey: "identiJson")
                            let distancia = article.Distancia
                           UserDefaults.standard.set(distancia, forKey: "distaJson")
                            
                            let userImage = UserDefaults.standard.string(forKey: "fotoJson")
                            let imageBase64 = UnaVezLogeadoViewController.convertBase64ToImage(imageString: userImage!)
                            self.imagenConductor.image = imageBase64
                            
                            /*
                            let nombre = UserDefaults.standard.string(forKey: "nombreJson")
                            let matricula = UserDefaults.standard.string(forKey: "matriJson")
                            let vehiculo = UserDefaults.standard.string(forKey: "vehiJson")
                            let modelo = UserDefaults.standard.string(forKey: "modeloJson")
                            let identificacion = UserDefaults.standard.string(forKey: "identiJson")
                            let distancia = UserDefaults.standard.string(forKey: "distaJson")
                            */
                            
                            self.nombreConductor.text = nombre
                            self.matriculaConductor.text = matricula
                            self.vehiculoConductor.text = vehiculo
                            self.modeloConductor.text = modelo
                            self.numeroTaxiConductor.text = identificacion
                            self.distanciaConductor.text = distancia
                            
                                break
                            }
                        
                    } else if  blog.Response == "false" {
                        self.displayAlert(title: "Usuario", message: "no hay conductores disponibles")
                    } else if  blog.Response == "nothing" {
                        self.displayAlert(title: "Información", message: "error red")
                    }
                    
                    
                }
            } catch {
                print("Error: Couldn't decode data into Blog:", error)
                return
            }
        }
        task.resume()
        
        
        
        
    }


что мне нужно сделать для разделения данных о доходах?.

Что я уже пробовал:

удалите из моей БД все драйверы и сохраните 1, и он работает, как я уже сказал в комментариях, он работает для одного драйвера.

переход на 4 json-х

    struct Blog: Decodable {
        let Response: String
        let articles: [Article]
        let articles2: [Article2]
        let articles3: [Article3]
        let articles4: [Article4]

        enum CodingKeys : String, CodingKey {
            case Response

            case articles = "Perfil1"
            case articles2 = "Perfil2"
            case articles3 = "Perfil3"
            case articles4 = "Perfil4"
        }
    }
    // id, nomnbre, matricula, vehiculo, modelo, identificacion,distancia

    struct Article: Decodable {
        let ID: String
        let Foto: String
        let Nombre: String
        let Matricula: String
        let Vehiculo: String
        let Modelo: String
        let Identificacion: String
        let Distancia: String

    }

    struct Article2: Decodable {
        let ID: String
        let Foto: String
        let Nombre: String
        let Matricula: String
        let Vehiculo: String
        let Modelo: String
        let Identificacion: String
        let Distancia: String

    }
    struct Article3: Decodable {
        let ID: String
        let Foto: String
        let Nombre: String
        let Matricula: String
        let Vehiculo: String
        let Modelo: String
        let Identificacion: String
        let Distancia: String

    }
    struct Article4: Decodable {
        let ID: String
        let Foto: String
        let Nombre: String
        let Matricula: String
        let Vehiculo: String
        let Modelo: String
        let Identificacion: String
        let Distancia: String

    }



    do {


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


        DispatchQueue.main.async {
            if blog.Response == "true" {
                for article2 in blog.articles2 {
                    let id2 = article2.ID
                     UserDefaults.standard.set(id2, forKey: "IdConductor2")
                    let foto2 = article2.Foto
                    UserDefaults.standard.set(foto2, forKey: "fotoConductor2")
                    let nombre2 = article2.Nombre
                    let matricula2 = article2.Matricula
                    let vehiculo2 = article2.Vehiculo
                    let modelo2 = article2.Modelo
                    let identificacion2 = article2.Identificacion
                    let distancia2 = article2.Distancia

                    self.perfil2Nombre.text = nombre2
                    self.perfil2Matricula.text = matricula2
                    self.perfil2Vehiculo.text = vehiculo2
                    self.perfil2Modelo.text = modelo2
                    self.perfil2Identificacion.text = identificacion2
                    self.perfil2Distancia.text = distancia2

                    let userImage = UserDefaults.standard.string(forKey: "fotoConductor2")
                    let imageBase64 = UnaVezLogeadoViewController.convertBase64ToImage(imageString: userImage!)
                    self.perfil2Image.image = imageBase64
                    break
                    for article3 in blog.articles3 {
                        let id3 = article3.ID
                        UserDefaults.standard.set(id3, forKey: "IdConductor3")
                        let foto3 = article3.Foto
                        UserDefaults.standard.set(foto3, forKey: "fotoConductor3")
                        let nombre3 = article3.Nombre
                        let matricula3 = article3.Matricula
                        let vehiculo3 = article3.Vehiculo
                        let modelo3 = article3.Modelo
                        let identificacion3 = article3.Identificacion
                        let distancia3 = article3.Distancia

                        self.perfil3Nombre.text = nombre3
                        self.perfil3Matricula.text = matricula3
                        self.perfil3Vehiculo.text = vehiculo3
                        self.perfil3Modelo.text = modelo3
                        self.perfil3Identificacion.text = identificacion3
                        self.perfil3Distancia.text = distancia3

                        let userImage = UserDefaults.standard.string(forKey: "fotoConductor3")
                        let imageBase64 = UnaVezLogeadoViewController.convertBase64ToImage(imageString: userImage!)
                        self.perfil3Imagen.image = imageBase64
                        break
                        for article4 in blog.articles4 {
                            let id4 = article4.ID
                            UserDefaults.standard.set(id4, forKey: "IdConductor4")
                            let foto4 = article4.Foto
                            UserDefaults.standard.set(foto4, forKey: "fotoConductor4")
                            let nombre4 = article4.Nombre
                            let matricula4 = article4.Matricula
                            let vehiculo4 = article4.Vehiculo
                            let modelo4 = article4.Modelo
                            let identificacion4 = article4.Identificacion
                            let distancia4 = article4.Distancia

                            self.perfil4Nombre.text = nombre4
                            self.perfil4Matricula.text = matricula4
                            self.perfil4Vehiculo.text = vehiculo4
                            self.perfil4Modelo.text = modelo4
                            self.perfil4Identificacion.text = identificacion4
                            self.perfil4Distancia.text = distancia4

                            let userImage = UserDefaults.standard.string(forKey: "fotoConductor4")
                            let imageBase64 = UnaVezLogeadoViewController.convertBase64ToImage(imageString: userImage!)
                            self.perfil4Imagen.image = imageBase64
                            break
                            for article in blog.articles {
                    let id = article.ID
                    UserDefaults.standard.set(id, forKey: "IdConductor1")
                    let foto = article.Foto
                    UserDefaults.standard.set(foto, forKey: "fotoConductor1")
                    let nombre = article.Nombre
                    UserDefaults.standard.set(nombre, forKey: "nombreJson")
                    let matricula = article.Matricula
                    UserDefaults.standard.set(matricula, forKey: "matriJson")
                    let vehiculo = article.Vehiculo
                    UserDefaults.standard.set(vehiculo, forKey: "vehiJson")
                    let modelo = article.Modelo
                    UserDefaults.standard.set(modelo, forKey: "modeloJson")
                    let identificacion = article.Identificacion
                    UserDefaults.standard.set(identificacion, forKey: "identiJson")
                    let distancia = article.Distancia
                   UserDefaults.standard.set(distancia, forKey: "distaJson")

                    let userImage = UserDefaults.standard.string(forKey: "fotoConductor1")
                    let imageBase64 = UnaVezLogeadoViewController.convertBase64ToImage(imageString: userImage!)
                    self.imagenConductor.image = imageBase64

                    /*
                    let nombre = UserDefaults.standard.string(forKey: "nombreJson")
                    let matricula = UserDefaults.standard.string(forKey: "matriJson")
                    let vehiculo = UserDefaults.standard.string(forKey: "vehiJson")
                    let modelo = UserDefaults.standard.string(forKey: "modeloJson")
                    let identificacion = UserDefaults.standard.string(forKey: "identiJson")
                    let distancia = UserDefaults.standard.string(forKey: "distaJson")
                    */

                    self.nombreConductor.text = nombre
                    self.matriculaConductor.text = matricula
                    self.vehiculoConductor.text = vehiculo
                    self.modeloConductor.text = modelo
                    self.numeroTaxiConductor.text = identificacion
                    self.distanciaConductor.text = distancia
                        break
                    }
                        }}}} else if  blog.Response == "false" {
                self.displayAlert(title: "Usuario", message: "no hay conductores disponibles")
            } else if  blog.Response == "nothing" {
                self.displayAlert(title: "Información", message: "error red")
            }


        }
    } catch {
        print("Error: Couldn't decode data into Blog:", error)
        return
    }
}
task.resume()

Richard Deeming

},';   // as you can see it is separeted with a ','
"ID":"'.$row[0].'",


Ты упускаешь возможность открыть дверь { символ для следующего объекта.

Вам также нужно будет обернуть свой список объектов в [...] символы, чтобы сделать его допустимым JSON.

0 Ответов