100

I have a trouble finding a way how to parse JSONArray. It looks like this:

[{"name":"name1","url":"url1"},{"name":"name2","url":"url2"},...]

I know how to parse it if the JSON was written differently (In other words, if I had json object returned instead of an array of objects). But it's all I have and have to go with it.

*EDIT: It is a valid json. I made an iPhone app using this json, now I need to do it for Android and cannot figure it out. There are a lot of examples out there, but they are all JSONObject related. I need something for JSONArray.

Can somebody please give me some hint, or a tutorial or an example?

Much appreciated !

5
  • 1
    Try this to see if your json is valid json.parser.online.fr Commented Sep 24, 2013 at 9:02
  • are you using any library for parsing json? Use gson library for json parsing.Much Helpfull. Commented Sep 24, 2013 at 9:03
  • It is valid. I parsed it in an app i did for an iPhone And it's working. I just dont know how to do it in Android Commented Sep 24, 2013 at 9:03
  • 1
    @nikash, yeah i noticed i could use gson. only problem is, all examples i found are for parsing a JSONObject not JSONArray Commented Sep 24, 2013 at 9:04
  • Post your code that you have tried so far.It will be helpful to give a precise answer accordingly. Commented Sep 24, 2013 at 9:09

11 Answers 11

164

use the following snippet to parse the JsonArray.

JSONArray jsonarray = new JSONArray(jsonStr);
for (int i = 0; i < jsonarray.length(); i++) {
    JSONObject jsonobject = jsonarray.getJSONObject(i);
    String name = jsonobject.getString("name");
    String url = jsonobject.getString("url");
}
Sign up to request clarification or add additional context in comments.

2 Comments

just one question if jsonarray includes numerics like [2].[4] and that numerics inside includes again an array so if i want to retrieve from especially lets say the array nested in numeric [4] in java code i must write int i=4???
@BiggDawgg: Glad it helped you. Post your question in a separate thread with JSON data so that it would be easy for me to answer.
27

I'll just give a little Jackson example:

First create a data holder which has the fields from JSON string

// imports
// ...
@JsonIgnoreProperties(ignoreUnknown = true)
public class MyDataHolder {
    @JsonProperty("name")
    public String mName;

    @JsonProperty("url")
    public String mUrl;
}

And parse list of MyDataHolders

String jsonString = // your json
ObjectMapper mapper = new ObjectMapper();
List<MyDataHolder> list = mapper.readValue(jsonString, 
    new TypeReference<ArrayList<MyDataHolder>>() {});

Using list items

String firstName = list.get(0).mName;
String secondName = list.get(1).mName;

5 Comments

Can you give me an example how would i get JSON as a string from url i have, please ?
The DefaultHttpClients execute-method is a blocking call so it has to be done in a background task, just to make clear why it is in separate class.
Im being given an error about the constructor of HttpGetTask. "The constructor HttpGetTask(OnHttpGetCompletedListener) refers to the missing type OnHttpGetCompletedListener"
have you imported OnHttpGetCompletedListener? Like this import your_package_name_here.HttpGetTask.OnHttpGetCompletedListener;
Yeap, that was the problem... Thanks for solving my issue :)
22
public static void main(String[] args) throws JSONException {
    String str = "[{\"name\":\"name1\",\"url\":\"url1\"},{\"name\":\"name2\",\"url\":\"url2\"}]";

    JSONArray jsonarray = new JSONArray(str);


    for(int i=0; i<jsonarray.length(); i++){
        JSONObject obj = jsonarray.getJSONObject(i);

        String name = obj.getString("name");
        String url = obj.getString("url");

        System.out.println(name);
        System.out.println(url);
    }   
}   

Output:

name1
url1
name2
url2

Comments

12

Create a class to hold the objects.

public class Person{
   private String name;
   private String url;
   //Get & Set methods for each field
}

Then deserialize as follows:

Gson gson = new Gson();
Person[] person = gson.fromJson(input, Person[].class); //input is your String

Reference Article: http://blog.patrickbaumann.com/2011/11/gson-array-deserialization/

2 Comments

I asume this "input" would be URL to that json? or is it something else?
This is a very simple solution. It should be the accepted one in my view
6

In this example there are several objects inside one json array. That is,

This is the json array: [{"name":"name1","url":"url1"},{"name":"name2","url":"url2"},...]

This is one object: {"name":"name1","url":"url1"}

Assuming that you have got the result to a String variable called jSonResultString:

JSONArray arr = new JSONArray(jSonResultString);

  //loop through each object
  for (int i=0; i<arr.length(); i++){

  JSONObject jsonProductObject = arr.getJSONObject(i);
  String name = jsonProductObject.getString("name");
  String url = jsonProductObject.getString("url");


}

2 Comments

Im having a hard time getting my JSONstring from URL. Maybe you could help with that?
Thank you for breaking it down with examples, good clarity
6
public class CustomerInfo 
{   
    @SerializedName("customerid")
    public String customerid;
    @SerializedName("picture")
    public String picture;

    @SerializedName("location")
    public String location;

    public CustomerInfo()
    {}
}

And when you get the result; parse like this

List<CustomerInfo> customers = null;
customers = (List<CustomerInfo>)gson.fromJson(result, new TypeToken<List<CustomerInfo>>() {}.getType());

3 Comments

Result variable is your JSONArray String
Would result variable be the url i need to fetch json from or already fetched json ?
by far the easiest solution
3

A few great suggestions are already mentioned. Using GSON is really handy indeed, and to make life even easier you can try this website It's called jsonschema2pojo and does exactly that:

You give it your json and it generates a java object that can paste in your project. You can select GSON to annotate your variables, so extracting the object from your json gets even easier!

Comments

2

My case Load From Server Example..

int jsonLength = Integer.parseInt(jsonObject.getString("number_of_messages"));
            if (jsonLength != 1) {
                for (int i = 0; i < jsonLength; i++) {
                    JSONArray jsonArray = new JSONArray(jsonObject.getString("messages"));
                    JSONObject resJson = (JSONObject) jsonArray.get(i);
                    //addItem(resJson.getString("message"), resJson.getString("name"), resJson.getString("created_at"));
                }

1 Comment

p.s "jsonObject.getString("messages")" type is jsonArray; first exist answer is cannot be convert string to jsonArray; i'm fix it.
-1

Create a POJO Java Class for the objects in the list like so:

class NameUrlClass{
       private String name;
       private String url;
       //Constructor
       public NameUrlClass(String name,String url){
              this.name = name;
              this.url = url; 
        }
}

Now simply create a List of NameUrlClass and initialize it to an ArrayList like so:

List<NameUrlClass> obj = new ArrayList<NameUrlClass>;

You can use store the JSON array in this object

obj = JSONArray;//[{"name":"name1","url":"url1"}{"name":"name2","url":"url2"},...]

1 Comment

It's not clear what obj = JSONArray; is supposed to do. What is JSONArray in this context? Where does it come from? What is the purpose of initializing obj with a new ArrayList<NameUrlClass>, when you replace it directly afterwards anyways?
-3

Old post I know, but unless I've misunderstood the question, this should do the trick:

s = '[{"name":"name1","url":"url1"},{"name":"name2","url":"url2"}]';
eval("array=" + s);
for (var i = 0; i < array.length; i++) {
for (var index in array[i]) {
    alert(array[i][index]);
}

}

Comments

-3
            URL url = new URL("your URL");
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            InputStream stream = connection.getInputStream();
            BufferedReader reader;
            reader = new BufferedReader(new InputStreamReader(stream));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            //setting the json string
            String finalJson = buffer.toString();

            //this is your string get the pattern from buffer.
            JSONArray jsonarray = new JSONArray(finalJson);

Comments

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.