Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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 –  Yume117 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
add comment

6 Answers

up vote 3 down vote accepted

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
1  
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
show 2 more comments

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
add comment

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
add comment

@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
add comment

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
add comment
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
add comment

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.