Turn Jsonobject into Jsonarray

Asked

Viewed 529 times

2

How do I get the data from this Json? I want to turn it into a Jsonarray to go through, but it’s 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"}
}

3 answers

2

From what I understand, you already have this JSON and want to 'transform' it from JSONObject for 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 JSONArray resulting 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}
]
  • thank you very much I managed

  • No problem, I’ll thank you to mark it as correct.

  • 1

    Just note that this format will only work if the Jsonobject keys are numbers, sequential and started in 1. for(int i = 1; i <= json.lenght(); i++) {&#xA; array.put(json.getJSONObject(""+i));&#xA;}

  • yes yes... thank you very much

1

Try this way:

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

Test with your json and see if the exit will be 1. I hope it helps

  • Worst q didn’t work I don’t know why else thanks for the help

  • maybe your array notation is incorrect the correct one would be []. Take a look at this link https://www.w3schools.com/js/js_json_arrays.asp

  • got it now thanks

1

To turn a Jsonobject into Jsonarray you will have to go through all the keys and go adding the children in Jsonarray.

Thus:

{"1":{"a":1,"c":0},"2":{"a":1,"c":0},"3":{"a":1,"c":0}} // JSONObject que será tranformado

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 assemble Jsonobject. Since you already have it, you won’t have to do it. I then declare Jsonarray. Finally, I go through the Jsonobject keys by adding your children to Jsonarray.

At the end you will have your Jsonarray as follows:

[{"a":1,"c":0},{"a":1,"c":0},{"a":1,"c":0}]

Browser other questions tagged

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