2

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?

2
  • Iterate on the inner JSON. Commented May 18, 2015 at 14:27
  • @maxZoom I have seen this and it does not solve my problem but thank you anyway for pointing this out . I can do that but i want to send the full array as an argument Commented May 18, 2015 at 14:32

2 Answers 2

3

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 :-)

Sign up to request clarification or add additional context in comments.

Comments

2

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;
  }
}

3 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.