How to decode a JSON array [{}, {}] on my android

0

How do I transform this string into an array on my Android so that I can manipulate it?

[{"id":"1","login":"Admin","senha":"Admin","nome":"Admin","msg":"Eba","logado":"0"},
{"id":"7","login":"Daniel","senha":"1234","nome":"Daniel","msg":"","logado":"0"},
{"id":"8","login":"Dannark","senha":"1234","nome":"Dannark","msg":"","logado":"0"},
{"id":"9","login":"Joosi","senha":"99487452","nome":"Joosi","msg":"","logado":"0"}]

I've been trying this way:

    /*Conn.response é a minha array*/
    JSONObject object = (JSONObject) new JSONTokener(Conn.response).nextValue();
    id = object.getString("0");
    nome = object.getString("3");
    msg = object.getString("4");

But it only works in the following format:

{"0":"1","1":"Admin","2":"1234","3":"Adm","4":"message","5":"0"}
    
asked by anonymous 20.05.2014 / 18:17

2 answers

1

Use JSONArray instead of JSONObject , using the JSONArray (java.lang.String) .

In your example it would look like this:

JSONArray array = new JSONArray(Conn.response);

Assuming that Conn.response is of type String . Where each element of JSONArray is JSONObject .

To access the values:

JSONObject object = array.getJSONObject(0);

String id = object.getString("id");
String login = object.getString("login");
//... E por assim para cada campo que quiser do objeto.
    
20.05.2014 / 18:28
0

I recommend using G , here's an example:

1.- Instantiate an object Gson :

Gson gson = new Gson();

2.- Get the corresponding Tipo for you, for example List<String[]> (Note that you can not do something like List<String[]>.class due to Java type of erasure ):

Type type = new TypeToken<List<String[]>>() {}.getType();

3.- Finally, convert from JSON to% defined_default:

List<String[]> yourList = gson.fromJson(yourJsonString, type);

Source: Here

    
20.05.2014 / 19:00