Problem when wanting to read JSON made PHP from Java

0

I'm trying to get a JSON from PHP, which returns the result of a query (SELECT) from a database.

I am using GSON, to convert the obtained JSON to an object in Java.

My problem is that it does not let me create the objects and returns an Exception. Nose if what PHP returns gives me back in a correct format to be interpreted in GSON.

What if at the moment of seeing the JSON in console to see what it gives back to me, it puts a kind of point at the beginning and another at the end, which if I take it out, it goes perfectly, but I would like to know what it can be the error and that I may be doing wrong.

MY PHP is as follows:

<?php
$servidor="localhost";
$nombre_bd="test2";
$username="root";
$password="";
$conexion = mysql_connect($servidor, $username, $password) or die ("No se ha podido conectar al servidor de Base de datos");
  
mysql_select_db($nombre_bd, $conexion) or die ("xD");
$sql = "SELECT * FROM usuario";
$result = mysql_query($sql, $conexion);
$array = array();
$i = 0;
while($row = mysql_fetch_array($result)) {
  $array[$i] = $row;
  $i ++;
}
$json = json_encode($array, JSON_FORCE_OBJECT);
echo $json;
?>

The Java from which I make the request:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package prueba.comsumir.webservice;

import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

/**
 *
 * @author Pablo
 */
public class PruebaComsumirWebservice {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Usuario usuario = new Usuario(1, "User1", "123");
        System.out.println(usuario.toString());
        URL url;
        try {
            // Creando un objeto URL
            url = new URL("http://localhost:8080/Sitio%201/code.php");

            // Realizando la petición GET
            URLConnection con = url.openConnection();

            // Leyendo el resultado
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    con.getInputStream()));

            String linea;
            String json = "";
            while ((linea = in.readLine()) != null) {
                System.out.println(linea);
                json += linea;
            }
            //{"id":1,"usuario":"usuario1","contrasenia":"asd"}
            Usuario usuario1 = new Gson().fromJson(json, Usuario.class);
            System.out.println(usuario.getUsuario());
            
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
    

And the User class:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package prueba.comsumir.webservice;

/**
 *
 * @author Pablo
 */
public class Usuario {
    private int id;
    private String usuario;
    private String contrasenia;

    public Usuario(int id, String usuario, String contrasenia) {
        this.id = id;
        this.usuario = usuario;
        this.contrasenia = contrasenia;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsuario() {
        return usuario;
    }

    public void setUsuario(String usuario) {
        this.usuario = usuario;
    }

    public String getContrasenia() {
        return contrasenia;
    }

    public void setContrasenia(String contrasenia) {
        this.contrasenia = contrasenia;
    }

    @Override
    public String toString() {
        return String.format("id:%s, usuario:%s, contrasenia:%s", id, usuario, contrasenia);
    }
}

When I execute the code from Netbeans, it returns the following JSON: and it gives me the following Exception:

{"0":{"0":"1","id":"1","1":"user1","usuario":"user1","2":"asd","contrasenia":"asd"},"1":{"0":"2","id":"2","1":"user2","usuario":"user2","2":"dsa","contrasenia":"dsa"}}
Exception in thread "main" com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 169 path $
    at com.google.gson.Gson.assertFullConsumption(Gson.java:855)
    at com.google.gson.Gson.fromJson(Gson.java:845)
    at com.google.gson.Gson.fromJson(Gson.java:793)
    at com.google.gson.Gson.fromJson(Gson.java:765)
    at prueba.comsumir.webservice.PruebaComsumirWebservice.main(PruebaComsumirWebservice.java:48)
Caused by: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 169 path $
    at com.google.gson.stream.JsonReader.syntaxError(JsonReader.java:1567)
    at com.google.gson.stream.JsonReader.checkLenient(JsonReader.java:1416)
    at com.google.gson.stream.JsonReader.doPeek(JsonReader.java:546)
    at com.google.gson.stream.JsonReader.peek(JsonReader.java:429)
    at com.google.gson.Gson.assertFullConsumption(Gson.java:851)
    ... 4 more
C:\Users\Pablo\AppData\Local\NetBeans\Cache.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 1 second)

Greetings and thanks from now.

    
asked by Pablo Palma 19.10.2018 в 02:41
source

1 answer

0

In the original code you are returning the records as an array (not as an associative array) that is why they arrive with a numeric index. And I do not know why the attributes are added, maybe it's the JSON_FORCE_OBJECT in json_encode .

On the other hand, in the example, I use mysqli instead of mysql, which has been deprecated for a long time.

$con=mysqli_connect($servidor,$username,$password,$nombre_bd);

if(!$con) die('error conectando');

$sql = "SELECT * FROM usuario";
$result = mysqli_query($con, $sql);

$rtn = array();

if($result){
    $row=mysqli_fetch_assoc($result);
    while($row !== null){
      $rtn[] = $row;
      $row=mysqli_fetch_assoc($result);
    }
    mysqli_close($con);
}

header('Content-Type: application/json');
return json_encode($rtn);

On the java side, you're going to need two classes:

Usuario , which you already have and Usuarios that the list has.

public class Usuarios{
    private List<Usuario> usuarios;
    // getter & setter
}

And the deserialization:

//{"id":1, "usuario":"usuario1", "contrasenia":"asd"}
Usuarios usuarios = new Gson().fromJson(json, Usuarios.class);
    
answered by 19.10.2018 в 07:27