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

Asked

Viewed 1,994 times

0

How I turn this string in an array on my Android so 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");

However, it only works in the following format:

{"0":"1","1":"Admin","2":"1234","3":"Adm","4":"message","5":"0"}
  • You need to add more information. How your array is declared Conn?

  • 1

    Jorge B. Actually the variable Conn.resonse is a string, and that would need to transfer it into an array

2 answers

1


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

In your example it would look like this:

JSONArray array = new JSONArray(Conn.response);

Assuming Conn.response is the type String. Where each element of JSONArray is a 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.
  • Really Conn.Response is String type, but how could I get the values? Not getting it with id = array.getString("0")

  • Okay, I’ve added an example of how to access object fields in the array. Remember that in the array, each element is a Jsonobject with its properties.

  • Hey buddy, you’re wild, it worked perfectly! I still have to try to understand the Code, but now I can get the value of any field, Thank you very much.

0

I recommend using the Gson, here’s an example:

1.- Install an object Gson:

Gson gson = new Gson();

2.- Take the Tipo corresponding is for you, for example List<String[]> (Note that you can’t do something like List<String[]>.class due to type of Java rip):

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

3.- Finally, convert from JSON to tipo defined:

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

Source: Here

Browser other questions tagged

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