Transform JsonObject into JsonArray

2

How do I get the data from this Json? I want to transform into a JsonArray to be able to scroll through, but it is a JsonObject ...

{
  "1":{"a":"1","c":"0","d":"0","m":"0","ns":"0","proc":"0"},   
  "2":{"a":"1","c":"0","d":"0","m":"0","ns":"0","proc":"0"},  
  "3":{"a":"1","c":"0","d":"0","m":"0","ns":"0","proc":"0"},    
  "4":{"a":"1","c":"0","d":"0","m":"0","ns":"0","proc":"0"},   
  "5":{"a":"1","c":"0","d":"0","m":"0","ns":"0","proc":"0"}
}
    
asked by anonymous 19.12.2017 / 14:37

3 answers

2

So I understand, you already have this JSON and want to 'transform' it from JSONObject to JSONArray .

Following, can be done as follows.

JSONObject json; // <- O seu JSONObject
JSONArray array = new JSONArray(); // JSONArray com os objetos
for(int i = 1; i <= json.lenght(); i++) {
    array.put(json.getJSONObject(""+i));
}

Your resulting JSONArray will look something like this:

[
    {"a":1,"c":0,"d":0,"m":0,"ns":0,"proc":0},
    {"a":1,"c":0,"d":0,"m":0,"ns":0,"proc":0},
    {"a":1,"c":0,"d":0,"m":0,"ns":0,"proc":0}
]
    
19.12.2017 / 17:43
1

Try this:

JSONObject jsonObject = new JSONObject("my json");
JSONArray jsonArray = jsonObject.getJSONArray("1");
jsonArray.getString(0);// 1

Test with your json and see if the output will be 1. Hope it helps

    
19.12.2017 / 14:46
1

To transform a JSONObject into JSONArray you will have to go through all the keys and add the children in the JSONArray.

This way:

  

{"1": {"a": 1, "c": 0}, "2": {"a": 1, "c": 0}, "3": {"a": 1 , "c": 0}} // JSONObject to be transformed

JSONObject json = new JSONObject();

json.put("1", new JSONObject() {{
    put("a", 1);
    put("c", 0);
}});
json.put("2", new JSONObject() {{
    put("a", 1);
    put("c", 0);
}});
json.put("3", new JSONObject() {{
    put("a", 1);
    put("c", 0);
}});

JSONArray jsonArray = new JSONArray();

// Percorre as chaves do JSONObject e vai adicionando os filhos no JSONArray.
for (String key : JSONObject.getNames(json)) {
    jsonArray.put(json.getJSONObject(key));
}

// Exibe o conteúdo do jsonArray
System.out.println(jsonArray);

The first step is to mount the JSONObject. As you already have it, you will not have to do this. Then declare the JSONArray. Finally, I run the JSONObject keys by adding their children to the JSONArray.

At the end you will have your JSONArray as follows:

  

19.12.2017 / 17:07