How to transform this Json into an object Arraylist?

Asked

Viewed 2,946 times

3

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

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 receive the data by android I’m not able to in any way turn it into a vector or an Arraylist of my class users.

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 Testeusuarios[] or an Arraylist ?

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

NOTE²: Suggestions to improve the code in php, are very welcome as well, because I tried to work with arrays and it returned in the "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 that someone who is having the same problem can take advantage since post.

1 answer

2


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

  • deserialize in a 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 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}]
  • I will reply your comment in the main post, showing the error presented. Thank you for the reply.

  • Sorry, but I didn’t understand exactly how to solve that problem, I re-did the Json and keeps giving error: $result = array(array(5, "Raphael", "M"), array(6, "Test", "M"));

  • I, in php, can’t help. See how json should look when editing the answer.

  • 1

    With your answer on the main topic I managed to solve my problem, thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.