Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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 !

share|improve this question
1  
Try this to see if your json is valid json.parser.online.fr – An-droid Sep 24 '13 at 9:02
    
are you using any library for parsing json? Use gson library for json parsing.Much Helpfull. – nilkash Sep 24 '13 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 – SteBra Sep 24 '13 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 – SteBra Sep 24 '13 at 9:04
    
Post your code that you have tried so far.It will be helpful to give a precise answer accordingly. – Spring Breaker Sep 24 '13 at 9:09

10 Answers 10

up vote 28 down vote accepted

use the following snippet to parse the JsonArray.

for (int i = 0; i < jsonarray.length(); i++) {
    JSONObject jsonobject = jsonarray.getJSONObject(i);
    String name = jsonobject.getString("name");
    String url = jsonobject.getString("url");
}

Hope it helps.

share|improve this answer
    
Great Worked for me!!! Thanks Spring Breaker – Pratap A.K Oct 18 '14 at 13:34
    
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 Feb 17 '15 at 19:36
    
@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. – Spring Breaker Feb 18 '15 at 5:24
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
share|improve this answer

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;
share|improve this answer
    
Can you give me an example how would i get JSON as a string from url i have, please ? – SteBra Sep 24 '13 at 10:37
2  
Weeell here's something that I made up: pastebin.com/w4thyPVK – vilpe89 Sep 24 '13 at 11:24
1  
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. – vilpe89 Sep 24 '13 at 11:39
    
Im being given an error about the constructor of HttpGetTask. "The constructor HttpGetTask(OnHttpGetCompletedListener) refers to the missing type OnHttpGetCompletedListener" – SteBra Sep 24 '13 at 12:41
1  
have you imported OnHttpGetCompletedListener? Like this import your_package_name_here.HttpGetTask.OnHttpGetCompletedListener; – vilpe89 Sep 24 '13 at 12:45

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/

share|improve this answer
    
I asume this "input" would be URL to that json? or is it something else? – SteBra Sep 24 '13 at 9:09
    
@Stebra, Exactly, I included that as a comment in the code. – Kevin Bowersox Sep 24 '13 at 9:09

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");


}
share|improve this answer
    
did you try this? – TharakaNirmana Sep 24 '13 at 9:16
    
Im having a hard time getting my JSONstring from URL. Maybe you could help with that? – SteBra Sep 24 '13 at 10:49
    
Send me the URL – TharakaNirmana Sep 24 '13 at 11:00

@Stebra See this example. This may help you.

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());
share|improve this answer
1  
Result variable is your JSONArray String – nilkash Sep 24 '13 at 9:10
    
Would result variable be the url i need to fetch json from or already fetched json ? – SteBra Sep 24 '13 at 9:22
1  
result string is already fetched JSONArray string – nilkash Sep 24 '13 at 9:25

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!

share|improve this answer

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

Hope it help

share|improve this answer
    
p.s "jsonObject.getString("messages")" type is jsonArray; first exist answer is cannot be convert string to jsonArray; i'm fix it. – bong jae choe Nov 5 '15 at 5:10

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

}

share|improve this answer
            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);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.