Parse json from internal resource file - android
I am beginner, trying to parse this json from a resource file, but no success. I can read the json but not parse it.
My json:
{"kind": "response",
"columns": [
"name",
"kml_4326"
],
"rows": [
[
"Spain",
{
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
61.211,
35.65,
0.0
],
[
62.231,
35.271,
0.0
],
[
62.985,
35.404,
0.0
]... etc...
My code:
try {
InputStream is = getResources().openRawResource(R.raw.bb);
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
is.close();
}
try {
JSONObject aJson = new JSONObject(writer.toString());
JSONArray json = aJson.getJSONArray("rows");
for (int i = 0; i < json.length(); i++) {
JSONObject object = json.getJSONObject(i); // problem is here
JSONObject bJson = new JSONObject(object.toString());
JSONArray cJson = new JSONArray(bJson);
JSONObject object1 = cJson.getJSONObject(1);
JSONArray geometry = object1.getJSONArray("geometry");
}
}
catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
// The error: JSONArray cannot be converted to JSONObject
org.json.JSONException: Value ["Spain",{"geometry":{"type":"Polygon","coordinates":[[[61.211,35.65,0],[62.231,35.271,0],[62.985,35.404,0],[63.194,35.857,0],[63.983,36.008,0],[64.546,36.312,0],[64.746,37.112,0],[65.589,37.305,0],[65.746,37.661,0],[66.217,37.394,0],[66.519,37.363,0],[67.076,37.356,0],[67.83,37.145,0],[68.136,37.023,0],[68.859,37.344,0],[69.196,37.151,0],[69.519,37.609,0],[70.117,37.588,0],[70.271,37.735,0],[70.376,38.138,0],[70.807,38.486,0],[71.348,38.259,0],[71.239,37.953,0],[71.542,37.906,0],[71.449,37.066,0],[71.845,36.738,0],[72.193,36.948,0],[72.637,37.048,0],[73.26,37.495,0],[73.949,37.422,0],[74.98,37.42,0],[75.158,37.133,0],[74.576,37.021,0],[74.068,36.836,0],[72.92,36.72,0],[71.846,36.51,0],[71.262,36.074,0],[71.499,35.651,0],[71.613,35.153,0],[71.115,34.733,0],[71.157,34.349,0],[70.882,33.989,0],[69.931,34.02,0],[70.324,33.359,0],[69.687,33.105,0],[69.263,32.502,0],[69.318,31.901,0],[68.927,31.62,0],[68.557,31.713,0],[67.793,31.583,0],[67.683,31.303,0],[66.939,31.305,0],[66.381,30.739,0],[66.346,29.888,0],[65.047,29.472,0],[64.35,29.56,0],[64.148,29.341,0],[63.55,29.468,0],[62.55,29.319,0],[60.874,29.829,0],[61.781,30.736,0],[61.699,31.38,0],[60.942,31.548,0],[60.864,32.183,0],[60.536,32.981,0],[60.964,33.529,0],[60.528,33.676,0],[60.803,34.404,0],[61.211,35.65,0]]]}}] at 0 of type org.json.JSONArray cannot be converted to JSONObject
at org.json.JSON.typeMismatch(JSON.java:100)
at org.json.JSONArray.getJSONObject(JSONArray.java:525)
I want to parse this JSON array. How can I do this?
Can anyone please help me?
Thanks in advance.
That is some awful JSON, do you have any control of it? The problem you have arrays within arrays within arrays. Specifically your error is because "rows" is an array of arrays so you need to have an inner loop.
JSONObject aJson = new JSONObject(writer.toString());
JSONArray rowsArray = aJson.getJSONArray("rows");
for (int i = 0; i < rowsArray.length(); i++) {
JSONArray jsonArray = rowsArray.getJSONArray(i);
for(int x = 0; x < jsonArray.length(); x++){
JSONObject object = jsonArray.getJSONObject(x); // now it will be the entry for spain
JSONArray geometry = object.getJSONArray("geometry");
}
}
Coordinates is even worse because you have an array of arrays of arrays so it will require numerous loops.
Related
I want to read this JSONArray,little confused..please guide me
How to read the images and its corresponding positions "images": [ [ { "images_url": "http://provenlogic.info/tinder_web/public/uploads/e9275d47cf5efd929794caafc50e957982c47582.jpg", "position": "1" }, { "images_url": "http://provenlogic.info/tinder_web/public/uploads/c374561da8583a77b4d21ee4b06f30d1a3fac4bb.jpg", "position": "3" } ] ]
try { JSONArray jsonArray = rootObject.getJSONArray("images"); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); String imageUrl=jsonObject.getString("images_url"); String position=jsonObject.getString("position"); } } catch (Exception e) { e.printStackTrace(); } Happy Codding!!!
A JSON Object starts with a { and ends with a } while a JSON Array starts with a [ and ends with a ]. JSONArray jArray = json.getJSONArray("images").get; for(int i = 0; i < jArray.length;i++) { JSONObject jObj = jsonArray.getJSONObject(i); String imageUrl = jObj.getString("images_url"); String position = jObj.getString("position"); } You will need to wrap the whole JSON Handling inside a try/catch block. You might want to try http://jsonlint.com/, an online json validator and https://jsonformatter.curiousconcept.com/, an online json formatter to understand easily! Cheers!
First of all get the JsonArray by using array name "images" and get each Json object . try { JSONArray jsonArray = new JSONArray("result"); for(int i=0;i<jsonArray.length();i++){ JSONArray jsonArray1=jsonArray.getJSONArray(i); for(int j=0;j<jsonArray1.length();j++){ JSONObject jsonObject=jsonArray1.getJSONObject(j); String imageurl=jsonObject.getString("images_url"); String position=jsonObject.getString("position"); } } }catch (Exception e){ e.printStackTrace(); }
Error parsing JSON in my Android app?
I have string json like this : { "listResult": { "items": [ { "id": "629047db-66d9-4986-ba3f-c75554198138", "thumbnail": "http://maya-wdv-01.r.worldssl.net/39aa32db-6f50-4da1-8fd5-a5b001135b98/629047db-66d9-4986-ba3f-c75554198138/8cb69c17-0fdb-454c-bfb5-a5b9001a9d59.jpg" }, { "id": "fa872dc8-d2b3-4815-92ef-d90e903bc3d8", "thumbnail": "http://maya-wdv-01.r.worldssl.net/39aa32db-6f50-4da1-8fd5-a5b001135b98/fa872dc8-d2b3-4815-92ef-d90e903bc3d8/c510c24f-5bfd-4a64-8851-a5b90017a38d.jpg" } ], "totalItems": 34, "pageSize": 5, "pageNumber": 1, "totalPages": 7, "searchTerm": null } } I Try Parsing with code : try { JSONObject json = new JSONObject(response); String listResult = json.getString(Variabel.listResult); JSONArray items_obj = json.getJSONArray(Variabel.items); int jumlah_list_data = items_obj.length(); if (jumlah_list_data > 0) { for (int i = 0; i < jumlah_list_data; i++) { JSONObject obj = items_obj.getJSONObject(i); String id = obj.getString(Variabel.id); String thumbnail = obj.getString(Variabel.thumbnail); } } } catch (JSONException e) { e.printStackTrace(); } But I getting Error : org.json.JSONException: No value for items So how to solve it ? sorry for my English
Instead of: JSONObject json = new JSONObject(response); String listResult = json.getString(Variabel.listResult); JSONArray items_obj = json.getJSONArray(Variabel.items); you should have: JSONObject json = new JSONObject(response); JSONObject listResult = json.getJSONObject(Variabel.listResult); JSONArray items_obj = listResult.getJSONArray(Variabel.items);
Accordingly to the json you posted, items is direct child of listResult, so you have to use the JSONObject with key listResult to retrieve it. Change JSONArray items_obj = json.getJSONArray(Variabel.items); with JSONArray items_obj = listResult.getJSONArray(Variabel.items);
How to parse specific JSON data in Android?
This is my JSON data from a URL: [ { "title" : "65th Issue", "author": "అశోక్"}, { "title" : "64th Issue", "author": "రాము" }, { "title" : "63rd Issue", "author": "శ్రీను" } ] It is looking like a JSONArray but it does not have its name (Array name) to access. Could anyone tell me how can I parse this JSON data in android? Parsing Code InputStream inputStream = connection.getInputStream(); Reader reader = new InputStreamReader(inputStream); int contentLength = connection.getContentLength(); char [] charArray = new char[contentLength]; reader.read(charArray); String responseData = new String(charArray); try{ JSONArray jArray = new JSONArray(responseData); for(int i = 0; i < jArray.length(); i++) { String title = jArray.getJSONObject(i).getString("title"); } } catch (JSONException e) { Log.v(TAG, "JSON EXCEPTION"); }
String jsonString = ...; //This contains the above mentioned String. For JSON String, [] denotes an array, an {} denotes an object. In your case, the string starts with a [] thats means its an array, so we first get the JSONArray. JSONArray jArray = new JSONArray(jsonString); Now, if you see, the array has multiple strings beginning and ending with {}, that means that the array has multiple objects. So we run a loop over the array length to extract each object and then the key - value from the object. for(int i = 0; i < jArray.length(); i++) { String title = jArray.getJSONObject(i).getString("title"); } So, the complete code will be something like this : String jsonString = ...; //This contains the above mentioned String. JSONArray jArray = new JSONArray(jsonString); for(int i = 0; i < jArray.length(); i++) { String title = jArray.getJSONObject(i).getString("title"); } Edit 2 : String jsonString = "[\r\n { \"title\" : \"65th Issue\", \"author\": \"\u0C05\u0C36\u0C4B\u0C15\u0C4D\"},\r\n { \"title\" : \"64th Issue\", \"author\": \"\u0C30\u0C3E\u0C2E\u0C41\" },\r\n { \"title\" : \"63rd Issue\", \"author\": \"\u0C36\u0C4D\u0C30\u0C40\u0C28\u0C41\" }\r\n]"; try { JSONArray jArray = new JSONArray(jsonString); for (int i = 0; i < jArray.length(); i++) { String title = jArray.getJSONObject(i).getString("title"); Log.d(LOGTAG, title); } } catch (JSONException e) { e.printStackTrace(); }
Unable to parse JSON values in Android
I am facing some problem while parsing JSON values, Please find the JSON file below, { "Account": "xxx", "Account_desc": "xxx", "TimeZone": "GMT+05:30", "DeviceList": [ { "Device": "xttt", "Device_desc": "txtx", "EventData": [ { "Device": "xttt", "Timestamp": 1373539125, "Timestamp_date": "2013/07/11", "Timestamp_time": "16:08:45", "StatusCode": 61715, "StatusCode_hex": "0xF113", "StatusCode_desc": "Stop", "GPSPoint": "12.97887,77.51030", "GPSPoint_lat": 12.97887, "GPSPoint_lon": 77.51030, "Speed": 0.0, "Speed_units": "km/h", "Odometer": 3.416, "Odometer_units": "Km", "Geozone": "zone4", "Geozone_index": 0, "Address": "cxcxc", "DigitalInputMask": 251, "DigitalInputMask_hex": "0xFB", "Index": 0 } ] }, { "Device": "pppp", "Device_desc": "statstr", "EventData": [ { "Device": "pppp", "Timestamp": 1368870217, "Timestamp_date": "2013/05/18", "Timestamp_time": "15:13:37", "StatusCode": 61715, "StatusCode_hex": "0xF113", "StatusCode_desc": "Stop", "GPSPoint": "14.26281,80.11421", "GPSPoint_lat": 14.26281, "GPSPoint_lon": 80.11421, "Speed": 0.0, "Speed_units": "km/h", "Odometer": 373.874, "Odometer_units": "Km", "Geozone": "port", "Geozone_index": 0, "Address": "asdfsdfss", "Index": 0 } ] } ] } From the above JSON , I would like to have only "GPSPoint_lat","GPSPoint_lon" and "Device" in "EventData" So I did the coding as follows, JSONObject jsonObject = ApplicationContext.getHttpService() .readAsJson(s); // System.out.println("indexvalue:"+s.indexOf(1,5)); // JSONObject object = jsonObject.getJSONObject("DeviceList"); JSONArray jsonArray = jsonObject.getJSONArray("DeviceList"); JSONObject object = jsonArray.getJSONObject(0); JSONArray secondarray = object.getJSONArray("EventData"); for (int i = 0; i < secondarray.length(); i++) { try { System.out.println("Im..."); // System.out.println("Latitude:"+ ((JSONObject) // jsonArray.get(i)).getString("GPSPoint_lat")); // String id = ((JSONObject) // jsonArray.get(i)).getString("deviceID"); // arr = (JSONArray) jsonArray.get(i); JSONObject obj = secondarray.getJSONObject(i); String lat = obj.getString("GPSPoint_lat"); String lon = obj.getString("GPSPoint_lon"); ........//.. ...///......}} But problem in the above code is whenever I am executing I am getting the arraylength is 1, i.e., getting only one value I mean first Eventdata values. What i need in this is I would like to get all the "Eventdata" values. Please suggest me regarding this. Regards Priya
JSONObject object = jsonArray.getJSONObject(0); I am guessing at this point in the above code you are just fetching the data at the first index which is specified by '0'. Hence you get the length also as one. Try doing the object.getJSONArray() inside the loop with the index. Maybe that will help you get all the data inside "EventData". Hope this helps :)
Try this.. JSONArray jsonArray = jsonObject.getJSONArray("DeviceList"); for (int j = 0; j < jsonArray.length(); j++) { JSONObject object = jsonArray.getJSONObject(j); JSONArray secondarray = object.getJSONArray("EventData"); for (int i = 0; i < secondarray.length(); i++) { System.out.println("Im..."); // System.out.println("Latitude:"+ ((JSONObject) // jsonArray.get(i)).getString("GPSPoint_lat")); // String id = ((JSONObject) // jsonArray.get(i)).getString("deviceID"); // arr = (JSONArray) jsonArray.get(i); JSONObject obj = secondarray.getJSONObject(i); String lat = obj.getString("GPSPoint_lat"); String lon = obj.getString("GPSPoint_lon"); } }
For JSON parsing use following class. import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONObject; public class JSONParser { public JSONParser() { } JSONObject jObj; String json; InputStream is = null; public JSONObject getJsonFromUrl(String url) { // TODO Auto-generated method stub try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } catch (Exception e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString(); System.out.println("Json String : " + json); } catch (Exception e) { e.printStackTrace(); } try { jObj = new JSONObject(json); } catch (Exception e) { e.printStackTrace(); } return jObj; } } and in your MainActivity use following code to parse it. JSONParser parser = new JSONParser(); JSONObject o = parser.getJsonFromUrl("yourjsonurl"); String Account = o.getString("Account"); String Account_desc = o.getString("Account_desc"); JSONArray array = o.getJSONArray("DeviceList"); JSONObject o1 = array.getJSONObject(0); String Device = o1.getString("Device"); //Again you have JSONArray JSONArray a = o1.getJSONArray("EventData"); //Then get object form array at index 0. JSONObject obj = a.getJSONObject(0); Then get your data from this json object.
The problem in your JSON is that in eventData array you have 1 JSON object with alot of mappings and not allot of jsonObjects. If you wannt EventData to be a JSONArray with all .."Geozone": "zone4", "Geozone_index": 0, "Address": "cxcxc", "DigitalInputMask": 251, "DigitalInputMask_hex": "0xFB", "Index": 0... as JsonObject you need yo change the JSON to be as an array ..{"Geozone": "zone4"}, {"Geozone_index": 0}, {"Address": "cxcxc"}, {"DigitalInputMask": 251}, {"DigitalInputMask_hex": "0xFB"}, { "Index": 0} ...
JSONArray DeviceListArray = jsonObject.getJSONArray("DeviceList"); for (int i = 0; i < DeviceListArray.length(); i++) { JSONObject Deviceobject = DeviceListArray.getJSONObject(i); JSONArray EventDataArray = Deviceobject.getJSONArray("EventData"); for (int j= 0; j < EventDataArray.length(); j++) { JSONObject valueObj = EventDataArray.getJSONObject(j); String GPSPoint_lat = valueObj.getString("GPSPoint_lat"); String GPSPoint_lon = valueObj.getString("GPSPoint_lon"); String Device = valueObj.getString("Device"); // Store this three values in ArrayList } } }
Priya, Your json contains three objects and two arrays as follows Objects 1. Entire response 2. DeviceList 3. EventData Arrays Device List - holds arrays of devices Event Data - Arrays of events Now carefully look your JSON, that json contains N number of Devices but every device has one event, So you have to iterate DeviceList and then iterate event list. So that iteration should as follows. JSONObject jsonObject = ApplicationContext.getHttpService().readAsJson(s); JSONArray jsonDeviceListArray = jsonObject.getJSONArray("DeviceList"); int deviceCount = jsonDeviceListArray.length(); JSONObject jsonDeviceObj; JSONArray jsonEventList; for (int deviceIndex = 0; deviceIndex < deviceCount; deviceIndex++) { jsonDeviceObj = jsonDeviceListArray.getJSONObject(deviceIndex); //Here you can print device, device_desc from jsonDeviceObj jsonEventList = jsonDeviceObj.getJSONArray("EventData"); int eventCount = jsonEventList.length(); JSONObject jsonEventObj; for (int eventIndex = 0; eventIndex < eventCount; eventIndex++) { jsonEventObj = jsonEventList.getJSONObject(eventIndex); //Here you can print event info. } }
You have missing "" in your json data. All numbers should have "", as before parsing it is treated as string.
JSON PARSING IN ANDROID?
I need to parse Json in Android, as a newbie in Json as well as in Android I am unable to do so here is the json String: [ { "chapter": "1. General", "lessons": [ { "lesson": "1.1 " }, { "lesson": "1.2" }, { "lesson": "1.3" } ] }, { "chapter": "2.emergencies" } ] Here I just want to get the lessons array data. So any help will really be appreciated. Thanks
JSONObject jObject = new JSONObject(jsonString); JSONObject chapObject = jObject.getJSONObject("chapter"); Log.d("Chapt", chapObject.getString("chapter")); JSONArray lessonArray = popupObject.getJSONArray("lessons"); for (int i = 0; i < 3; i++) { Log.d("Name", lessonArray.getJSONObject(i).getString("lesson").toString()); Log.d("Value", lessonArray.getJSONObject(i).getString("onclick").toString()); } JSONObject chap2Object = jObject.getJSONObject("chapter"); Log.d("Chapt2", chapObject.getString("chapter"));
Use JSONObject and/or JSONArray. They can be created directly from strings, eg: JSONObject json = new JSONObject(string);
Android includes a JSON parser: http://developer.android.com/reference/org/json/package-summary.html String json = "{ ... }"; JSONObject obj = new JSONObject(json); JSONArray array = obj.getJSONArray("lessions"); for (int i = 0; i < array.length(); i++) { String lession = array.getJSONObject(i).getString("lession"); }