java – How to transform this Json num ArrayList of objects?

Question:

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

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

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

Code executed 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 get the data by android I'm not able to transform it in 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 can a "multiple query" become a UserTest[] 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 very welcome too, as I tried to work with arrays and it returned in the encode "ArrayArray".


Edit
The problem was solved with the answer from the branch, 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 that someone who is having the same problem can take advantage of this post.

Answer:

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

  • 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:

That your json to be considered as an array has to start with [ and end with ] and each item be separated by ,

[{"id": 1, "nome": Raphael, "sexo": M},{"id": 2, "nome": teste, "sexo": M}]
Scroll to Top