Convert JSONArray to arrayList

11,510

Solution 1

Aazelix, your Json output seem to be missing opening array bracket. Its correct form is listed below:

{"output":[{"name":"Name3","URI":"Value3"},{"name":"Name5","URI":"Value5"},{"name":"Name4","URI":"Value4"}]}

As for the conversion to POJO

List<MyObj> list = new ArrayList<>();
if (outputs!= null) { 
  int len = outputs.length();
  for (int i=0; i<len; i++) { 
    JSONObject o = (JSONObject) outputs.get(i);
    list.add(new MyObj(o.getString('name'), o.getString('URL')));
  } 
} 
System.out.println("There is " + list.size() + " objects.");
public static final class MyObj {
  final String name;
  final String url;
  public MyObj(String name, String url) {
     this.name = name;
     this.url  = url;
  }
}

Solution 2

It is not specified, which JSON parser do you use, so I suppose you can choose right now and I'll suggest using Gson as such.

The better solution for deserializing such a structures is creating a special class for each structure, for example:

public class NameURIPair {
    private String name;
    private String URI;
    // getters
}

Then your JSON can be deserialized into a class, which holds the resulting List in it:

public class Data {
    private List<NameURIPair> output;
    // getter
}
// ...
Data data = new Gson(stringData, Data.class);

Since you've requested the other way, you still can get just the parsed JSON into JsonElement with JsonParser

JsonElement root = new JsonParser().parse(stringData);

Although I won't give you the full solution not to appreciate this kind of solutions :-)

Share:
11,510

Related videos on Youtube

azelix
Author by

azelix

Updated on June 18, 2022

Comments

  • azelix
    azelix 4 months

    I'm trying to convert a JSONArray which looks like this :

    {"output":["name":"Name3","URI":"Value3"},{"name":"Name5","URI":"Value5"},{"name":"Name4","URI":"Value4"}]}
    

    Into an arrayList so for example the output of Arr[0][0] will be Name3

    I have tried this solution:

    if (outputs!= null) { 
        int len = outputs.length();
        for (int j=0;j<len;j++){ 
            list.add(outputs.get(j).toString());
        } 
    } 
    for (String str : list) {               
        System.out.println("Item is: " + str);              
    }
    

    But I get the full row : {"name":"Name3","URI":"Value3"}

    How can I get each object of my JSONArray?

  • Dmitry Ginzburg
    Dmitry Ginzburg over 7 years
    o.name; o.URL. Really?
  • Dmitry Ginzburg
    Dmitry Ginzburg over 7 years
    second poing: OP had URI, not URL
  • MaxZoom
    MaxZoom over 7 years
    I did not compile nor run the code so it may need some improvements.