How to transform this Json into an ArrayList of objects?

3

I'm working on a project where I'm doing a query in the database and need to return a list of database users to be listed in my application.

I have the following line Json (returned by the server):

{"id": 1, "nome": Raphael, "sexo": M}{"id": 2, "nome": teste, "sexo": M}

Code running on the server:

while($res = mysql_fetch_array($query))
    $result .= '{"id": '.$res['account_id'].', "nome": '.$res['nome'].', "sexo": '.$res['sexo']."}";

In the example I have 2 registered users, Raphael and test, but when I receive the data through the android, I can not make it into a vector or an ArrayList of my users class.

Class Code:

public class TesteUsuarios {
    String nome, sexo;
    int id;

    TesteUsuarios(int id, String nome, String sexo)
    {
        this.id = id;
        this.nome = nome;
        this.sexo = sexo;
    }
}

How to make a "multiple query" become a TestUsuarios [] or an ArrayList?

NOTE: I'm using the Gson API, and I've tried to find the solution for both it and the basic java functions.

NOTE: Suggestions to improve the code in php, are welcome too, as I tried to work with arrays and it returned in the encode "ArrayArray".

Edit
The problem was solved with the ramaral response, and a change in the php part of the code.

Change in php:

$result = array(array("id" => 5, "nome" => "Raphael", "sexo" => "M"), array("id" => 6, "nome" => "Teste", "sexo" => "M"));

Basically generate json from a multidimensional array.

I hope someone who is having the same problem can take advantage of it from post.

    
asked by anonymous 08.10.2016 / 08:45

1 answer

2

If you have the result in Json format in a string, use

  • deserialize in an array :

    Gson gson = new Gson();
    TesteUsuarios[] usuariosArray = gson.fromJson(jsonString, TesteUsuarios[].class);
    
  • Deserialize in a List :

    Gson gson = new Gson();
    Type usuariosListType = new TypeToken<ArrayList<TesteUsuarios>>(){}.getType(); 
    List<TesteUsuarios> usuariosList = gson.fromJson(jsonString, usuariosListType);
    

Note:

This json to be considered as an array must start with [ and end with ] and each item be separated by ,

[{"id": 1, "nome": Raphael, "sexo": M},{"id": 2, "nome": teste, "sexo": M}]
    
08.10.2016 / 12:35