How to parse JSON Array (Not Json Object) in Android

JavaAndroidJsonGsonArrays

Java Problem Overview


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 !

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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;

Solution 3 - Java

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

Solution 4 - Java

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/

Solution 5 - Java

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

Solution 6 - Java

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


}

Solution 7 - Java

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!

Solution 8 - Java

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

Solution 9 - Java

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"},...]

Solution 10 - Java

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

}

Solution 11 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSteBraView Question on Stackoverflow
Solution 1 - JavaSpring BreakerView Answer on Stackoverflow
Solution 2 - Javavilpe89View Answer on Stackoverflow
Solution 3 - JavaMaxim ShoustinView Answer on Stackoverflow
Solution 4 - JavaKevin BowersoxView Answer on Stackoverflow
Solution 5 - JavanilkashView Answer on Stackoverflow
Solution 6 - JavaTharakaNirmanaView Answer on Stackoverflow
Solution 7 - JavaTomCBView Answer on Stackoverflow
Solution 8 - Java최봉재View Answer on Stackoverflow
Solution 9 - JavaDevesh PradhanView Answer on Stackoverflow
Solution 10 - JavaJanusView Answer on Stackoverflow
Solution 11 - Javaboyke purnomoView Answer on Stackoverflow