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 !
511 Answers
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"); } 2I'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; 5public 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 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 2In 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"); } 2public 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()); 3A 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!
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")); } 1Create 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"},...] 1Old 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]); } }
0 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);