Unable to parse JSON values in Android - 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.

Related

Parse json from internal resource file

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.

Can't figure out this JSON parsing error

Currently I'm trying to display JSON data (hosted on a Webserver) in a ListView in Android. The App correctly receives the data but is unable to process it further to display it in said ListView.
The error is as follows:
JSON parsing error: Value ... of type org.json.JSONArray cannot be converted to JSONObject
The JSON data I'm trying to parse looks like the following:
[{"idBuch":1,"autor":"Erich Maria Remarque","name":"Im Westen nichts Neues","preis":20,"buchtyp":{"idBuchtyp":3,"typenamen":"Geschichte"}}]
The code that processes the received JSON-String:
try{
JSONObject jsonObject = new JSONObject(jsonStr);
JSONArray books = jsonObject.getJSONArray("book");
for(int i = 0; i < books.length(); i++){
JSONObject obj = books.getJSONObject(i);
String idBook = obj.getString("idBuch");
String author = obj.getString("autor");
String name = obj.getString("name");
String price = obj.getString("preis");
JSONObject booktype = obj.getJSONObject("buchtyp");
String idBooktype = booktype.getString("idBuchtyp");
String typename = booktype.getString("typenamen");
HashMap<String, String> book = new HashMap<>();
book.put("idBook", idBook);
book.put("author", author);
book.put("name", name);
book.put("price", price);
book.put("genre", typename);
bookList.add(book);
} }catch(final JSONException e)
I am aware of the fact that there are a lot of similar questions on this site but I still had no success regarding this issue. Thank you in advance.
The JSON that you provided only contains an array.
[
{
"idBuch": 1,
"autor": "Erich Maria Remarque",
"name": "Im Westen nichts Neues",
"preis": 20,
"buchtyp": {
"idBuchtyp": 3,
"typenamen": "Geschichte"
}
}
]
However, your code expects the root to be an object with field book.
{
"book": [
{
"idBuch": 1,
"autor": "Erich Maria Remarque",
"name": "Im Westen nichts Neues",
"preis": 20,
"buchtyp": {
"idBuchtyp": 3,
"typenamen": "Geschichte"
}
}
]
}
In this case, try replacing the line:
JSONObject jsonObject = new JSONObject(jsonStr);
with
JSONArray books = new JSONArray(jsonStr);
and proceed as normal. Your end result should look like:
try {
JSONArray books = new JSONArray(jsonStr);
for (int i = 0; i < books.length(); i++) {
JSONObject obj = books.getJSONObject(i);
String idBook = obj.getString("idBuch");
String author = obj.getString("autor");
String name = obj.getString("name");
String price = obj.getString("preis");
JSONObject booktype = obj.getJSONObject("buchtyp");
String idBooktype = booktype.getString("idBuchtyp");
String typename = booktype.getString("typenamen");
HashMap < String, String > book = new HashMap < > ();
book.put("idBook", idBook);
book.put("author", author);
book.put("name", name);
book.put("price", price);
book.put("genre", typename);
bookList.add(book);
}
} catch (final JSONException e) {
e.printStackTrace()
}

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

how to access multi array json file?

this is my code below how do i acess this json file check my method it is coreect method to aces json file array and nodes? i want to acess this json file below from my code help me how do i acess this json file formmy code? i dontknow howmany array in json file
{
"status":1,
"message":"",
"data":
{
"school":
[
{
"id":3,
"name":"FG Public School"
},
{
"id":4,
"name":"Fazaia Inter College"}
]
}
}
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(SelectMenuAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream =
response.getEntity().getContent();
BufferedReader in = new BufferedReader(new
InputStreamReader(atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null){
str += line;
}
JSONObject json = new JSONObject(str);
JSONArray data = json.getJSONArray("school");
for (int i = 0; i < data.length(); i++) {
JSONObject object =
data.getJSONObject(i);
// JSONObject category =
object.getJSONObject("Category");
Category_ID.add(Long.parseLong(object.getString("id")));
Category_name.add(object.getString("name"));
Log.d("Category name",
Category_name.get(i));
Try This Code
=================================================================
try {
String[] Id,name;
JSONObject json = new JSONObject(str);
JSONObject SubString3 = json.getJSONObject("data");
Log.e(SubString3.toString(),"SubString3");
JSONArray Array = SubString3.getJSONArray("school");
Id = new String[Array.length()];
name =new String[Array.length()];
for(int i=0;i<=Array.length();i++)
{
Id[i]= Array.getJSONObject(i).getString("id");
Log.e(Id[i].toString(),"Id[i]");
name[i]= Array.getJSONObject(i).getString("name");
Log.e(name[i].toString(),"name[i]");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The Category object is not present inside the Json file
you can try following
JSONObject json = new JSONObject("str");
JSONObject data = json.getJSONObject("data");
JSONArray school = json.getJSONArray("school");
for (int i = 0; i < data.length(); i++) {
JSONObject object = school.getJSONObject(i);
long id = Long.parseLong(object.getString("id"));
String name = object.getString("name");
JSONObject category = new JSONObject();
category.put("id");
category.put("name");
}
First you need to fetch an OBJECT of the whole JSON because it's in '{' '}'. Then you need to fetch an object again with the name "data" because it is in '{' '}'. And only then should you fetch the array named "school".
JSONObject json = new JSONObject(str);
JSONObject data = json.getJSONObject("data");
JSONArray school = data.getJSONArray("school");

How do I pull the string array from this json object?

I am trying to get a list of available numbers from the following json object, using the class from org.json
{
"response":true,
"state":1,
"data":
{
"CALLERID":"81101099",
"numbers":
[
"21344111","21772917",
"28511113","29274472",
"29843999","29845591",
"30870001","30870089",
"30870090","30870091"
]
}
}
My first steps were, after receiving the json object from the web service:
jsonObj = new JSONObject(response);
jsonData = jsonObj.optJSONObject("data");
Now, how do I save the string array of numbers?
use:
jsonObj = new JSONObject(response);
jsonData = jsonObj.optJSONObject("data");
JSONArray arrJson = jsonData.getJSONArray("numbers");
String[] arr = new String[arrJson.length()];
for(int i = 0; i < arrJson.length(); i++)
arr[i] = arrJson.getString(i);
you need to use JSONArray to pull data in an array
JSONObject jObj= new JSONObject(your_json_response);
JSONArray array = jObj.getJSONArray("data");
Assuming that you are trying to get it in a javascript block, Try something like this
var arrNumber = jsonData.numbers;
My code is for getting "data":
public void jsonParserArray(String json) {
String [] resultsNumbers = new String[100];
try {
JSONObject jsonObjectGetData = new JSONObject(json);
JSONObject jsonObjectGetNumbers = jsonObjectGetData.optJSONObject("results");
JSONArray jsonArray = jsonObjectGetNumbers.getJSONArray("numbers");
for (int i = 0; i < jsonArray.length(); i++) {
resultsNumbers[i] = jsonArray.getString(i);
}
} catch (JSONException e) {
e.printStackTrace();
Log.e(LOG_TAG, e.toString());
}
}

Categories

Resources