When I'm JSONObject jsonObj = new JSONObject(jsonStr);
I enter in catch because my json is not a array.
How can I get this format ?
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "http://10.0.2.2:8080/PFA/crimes";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray data = jsonObj.getJSONArray("crime");
// looping through All Contacts
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
String day_week = c.getString("day_week");
String naturecode = c.getString("naturecode");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("day_week", day_week);
contact.put("naturecode", naturecode);
// adding contact to contact list
List.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
JSON:
{
"crime": {
"compnos": "zerezrerzerezzr",
"day_week": "rtkeertoeirtj ,ertkierj",
"domestic": "false",
"fromdate": "ekrjtner",
"id": "1",
"location": "etritkjrtoijty",
"main_crimecode": "oijereriotjeroi",
"month": "455",
"naturecode": "zetzeeztet",
"reportingarea": "58",
"reptdistrict": "zorigjrgoijtoi",
"shift": "rektenrloj",
"shooting": "true",
"streetname": "kjrtnerkj",
"ucrpart": "irtjeroitejroirj",
"weapontype": "kejfnergkrtnh",
"x": "11",
"xstreetname": "zekjrnetk",
"y": "11",
"year": "45"
}
}
JsonObject crime = jsonObj.getJsonObject("crime");
JsonObject compnos = crime.getJsonObject("compnos");
.
..
...
There is no jsonArray in your json value. Give up to get jsonArray.
Try this:
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject jsonMetaObject = jsonMasterObject.getJSONObject("crime");
instead of
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray data = jsonObj.getJSONArray("crime");
Because you get jsonObject in key of crime not JsonArray.
Related
I am writing an Android application that pulls JSON data from an SQL db.
In my Async Task class, I receive a JSON string from an HTTP request and I assign it to a JSONObject. This string contains various data, including an array of coordinates which I need. After that, I do obj.getJSONArray("coordinates"); As soon as I do that, my application throws an exception:
org.json.JSONObject cannot be converted to JSONArray in android
I am following this post's approach to solve my issues but with no luck:
org.json.JSONObject cannot be converted to JSONArray in android
I feel like I need to iterate over my JSON string until I see that array. I will post the string data below.
protected Void doInBackground(Void... voids) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(address);
//Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject obj = new JSONObject(jsonStr);
JSONArray deviceJsonArray = obj.getJSONArray("coordinates"); //ERROR OCCURS HERE!
// looping through All Devices
for (int i = 0; i < deviceJsonArray.length(); i++) {
JSONObject json = deviceJsonArray.getJSONObject(i);
//String DeviceID = c.getString("id");
// longitude = json.getDouble("longitude");
// latitude = json.getDouble("latitude");
Device device = new Device();
device.setName(receivedDeviceName);
//Adding the information to the array.
coordinatesArray.add(device);
}
//Log.e(TAG, "arraylist: " + coordinatesArray);
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
JSON string value:
{"data":{"type":"gps","total_distance":18,"coordinates":[{"latitude":49.169209,"longitude":-122.990952,"time":"12:02:38 AM"},{"latitude":49.16922,"longitude":-122.990959,"time":"2:42:33 PM"},{"latitude":49.1693,"longitude":-122.988098,"time":"5:16:33 PM"},{"latitude":49.170979,"longitude":-122.968239,"time":"5:18:33 PM"},{"latitude":49.174992,"longitude":-122.962502,"time":"5:20:33 PM"},{"latitude":49.17688,"longitude":-122.95768,"time":"5:22:33 PM"},{"latitude":49.182232,"longitude":-122.960297,"time":"5:24:33 PM"},{"latitude":49.18581,"longitude":-122.950813,"time":"5:26:33 PM"},{"latitude":49.188869,"longitude":-122.945969,"time":"5:28:33 PM"},{"latitude":49.197689,"longitude":-122.948502,"time":"5:30:33 PM"},{"latitude":49.20216,"longitude":-122.947418,"time":"5:32:33 PM"},{"latitude":49.2071,"longitude":-122.949593,"time":"5:34:33 PM"},{"latitude":49.213051,"longitude":-122.938522,"time":"5:36:33 PM"},{"latitude":49.215462,"longitude":-122.93399,"time":"5:38:33 PM"},{"latitude":49.216381,"longitude":-122.932297,"time":"5:40:33 PM"},{"latitude":49.218769,"longitude":-122.92791,"time":"5:42:33 PM"},{"latitude":49.221062,"longitude":-122.923653,"time":"5:44:33 PM"},{"latitude":49.227119,"longitude":-122.912392,"time":"5:46:33 PM"},{"latitude":49.234489,"longitude":-122.89872,"time":"5:48:33 PM"},{"latitude":49.235699,"longitude":-122.894608,"time":"5:50:33 PM"},{"latitude":49.241928,"longitude":-122.89257,"time":"5:52:33 PM"},{"latitude":49.241871,"longitude":-122.89016,"time":"6:02:33 PM"}]}}
Could someone see what I am doing wrong or recommend a fix please?
Try this instead:
JSONObject obj = new JSONObject(jsonStr);
JSONObject objData = obj.getJSONObject("data");
JSONArray deviceJsonArray = objData.getJSONArray("coordinates");
The "coordinates" JSONArray is one element deeper in your JSON structure
This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 5 years ago.
I want parse this json and get the value of user :
name and base
"response": [
{
"user": {
"avatar": {
"base": "http://undermusic.ir/up/avatar/base_c966da5e756c4f79982cef797c317f369e97a7d78c4206426be8e09237433894file_avatar.jpg"
},
"name": "hadi",
}
Try something like this...
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0;i<jsonArray.length();i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
// String name = jsonObject.getString("")
JSONObject jsonObject1_user = jsonObject.getJSONObject("user");
JSONObject jsonObject1_avater = jsonObject1_user.getJSONObject("avatar");
String base = jsonObject1_avater.getString("base");
String name = jsonObject1_user.getString("name");
Log.d("getbase_name","values "+base+" "+name);
}
} catch (JSONException e) {
e.printStackTrace();
}
Extracting data from JsonArray,Try something like this.
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("response");
// Getting JSON User Object node
JSONObject userObj = contacts.getJSONObject("user");
//Getting name key from user object
String name = userObj.getString("name");
//Getting avatar node from user object
JSONObject avatarObj= userObj.getJSONObject("avatar");
//Getting base key from avatar object
String base= avatarObj.getString("base");
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
}
I have a JSONArray with a format like this:
[
{
"type": "fuel",
"name": "Esso",
"address": "Frankfurter Straße 65",
"lat": 49.8848387,
"lon": 8.6520691 },
{
"type": "amenity",
"name": "Hauptbahnhof",
"address": "Am Hauptbahnhof 20",
"lat": 49.8725,
"lon": 8.628889,
"icon": "bahnhof.jpg" }
]
and it goes on.
the moment I open the activity where I want my JSONArray to be in a Listview I get a Toast with the Message of my catchblock "error parsing: .." and it shows me the whole JSONFile in the toast.
Can someone explain me why this is happening, I can't find my mistake. I'll show you guys my Tryblock where the error gets catched.
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "...excluded link...";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("contacts");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String type = c.getString("type");
String name = c.getString("name");
String address = c.getString("address");
String lat = c.getString("lat");
String lon = c.getString("lon");
String icon = c.getString("icon");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("type", type);
contact.put("name", name);
contact.put("address", address );
contact.put("lat", lat);
contact.put("lon", lon);
contact.put("icon", icon);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
Assuming your JSON is correct it looks like:
{
"contacts": [
{
"type": "fuel",
"name": "Esso",
"address": "Frankfurter Straße 65",
"lat": 49.8848387,
"lon": 8.6520691
},
{
"type": "amenity",
"name": "Hauptbahnhof",
"address": "Am Hauptbahnhof 20",
"lat": 49.8725,
"lon": 8.628889,
"icon": "bahnhof.jpg"
}
]
}
now how to parse it using CHECK for KEY look at the code:
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("contacts");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String type = c.getString("type");
String name = c.getString("name");
String address = c.getString("address");
String lat = c.getString("lat");
String lon = c.getString("lon");
String icon;
if(c.has("icon")){
//your json is having "icon" Key, get the value
icon = c.getString("icon");
}
else{
//your json is NOT having "icon" Key, assign a dummy value
icon = "/default/icon_url(if_any)";
}
}
this will do, it will assign a default url of icon if any or any other string that you want to store in case icon is not present or you can leave it empty, and if icon exists, you will get the url.
you can ask for any doubts related to this answer.
Happy coding..:)
I want to get two json array from remote url
I am using AsyncTask to do that but i can't get any data !
#Override
protected Void doInBackground(String... params) {
try {
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
String json = jParser.getJSONFromUrl(params[0]);
// Getting Array of Contacts
data = new JSONArray(json);
JSONArray cities = data.getJSONArray();
// looping through All cities
for (int i = 0; i < cities.length(); i++) {
JSONObject e = cities.getJSONObject(i);
String ci_name = e.getString("ct_name");
String ci_web_id = e.getString("ct_id");
db.addCity(ci_name, ci_web_id);
db.closeDatabase();
}
JSONArray districts = data.getJSONArray(1);
// looping through All districts
for (int i = 0; i < districts.length(); i++) {
JSONObject e = districts.getJSONObject(i);
String di_name = e.getString("ar_name");
String di_web_id = e.getString("ar_id");
db.addDistrict(di_name, di_web_id);
db.closeDatabase();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
The return data is like that :
{"city":[
{"ct_id":"1432","ct_name":"\u062e\u0645\u064a\u0633 \u0645\u0634\u064a\u0637","ct_hide":"0","ct_ord":"0","ct_created":"0"},
{"ct_id":"1434","ct_name":"\u0639\u0633\u064a\u0631","ct_hide":"0","ct_ord":"0","ct_created":"0"},{"ct_id":"1435","ct_name":"\u0627\u0644\u0645\u0646\u0637\u0642\u0629 \u0627\u0644\u0634\u0631\u0642\u064a\u0629","ct_hide":"0","ct_ord":"0","ct_created":"0"}
], "area":[
{"ar_id":"1422","ar_name":"\u0627\u0644\u0645\u062f\u064a\u0646\u0629 \u0627\u0644\u0645\u0646\u0648\u0631\u0647","ar_hide":null,"ar_ord":null,"ar_created":null}, {"ar_id":"1433","ar_name":"\u0646\u062c\u0631\u0627\u0646","ar_hide":null,"ar_ord":null,"ar_created":null}]
}
Your json is a JSONObject not a JSONarray.
This
data = new JSONArray(json);
is wrong.
{ // json object node
"city": [ // json array city
{ // json object
"ct_id": "1432",
"ct_name": "خميس مشيط",
"ct_hide": "0",
"ct_ord": "0",
"ct_created": "0"
},
{
"ct_id": "1434",
"ct_name": "عسير",
"ct_hide": "0",
"ct_ord": "0",
"ct_created": "0"
},
{
"ct_id": "1435",
"ct_name": "المنطقة الشرقية",
"ct_hide": "0",
"ct_ord": "0",
"ct_created": "0"
}
],
"area": [ // json array area
{
"ar_id": "1422",
"ar_name": "المدينة المنوره",
"ar_hide": null,
"ar_ord": null,
"ar_created": null
},
{
"ar_id": "1433",
"ar_name": "نجران",
"ar_hide": null,
"ar_ord": null,
"ar_created": null
}
]
}
To parse
JSONObject jb = new JSONObject(json);
JSONArray city = jb.getJSONArray("city");
for(int i=0;i<city.length();i++)
{
JSONObject jb1 = city.getJSONObject(i);
String id = jb1.getString("ct_id");
String name = jb1.getString("ct_name");
String hide = jb1.getString("ct_hide");
String ord = jb1.getString("ct_ord");
String created = jb1.getString("ct_ord");
Log.i("city id is",id);
}
JSONArray area = jb.getJSONArray("area");
for(int i=0;i<area.length();i++)
{
JSONObject jb1 = area.getJSONObject(i);
String id = jb1.getString("ar_id");
String name = jb1.getString("ar_name");
String hide = jb1.getString("ar_hide");
String ord = jb1.getString("ar_ord");
String created = jb1.getString("ar_ord");
Log.i("Area id is",id);
}
You could also consider using gson to parse json to java objects
http://code.google.com/p/google-gson/
I don't see any request to remote url. How do you get data from your server?
Generally, it looks like this:
public void execute() {
final AndroidHttpClient client = AndroidHttpClient.newInstance("TAG");
try {
HttpUriRequest request = getRequest();
HttpResponse response = client.execute(request);
final int code = response.getStatusLine().getStatusCode();
Log.d("TAG", "Server returns " + code);
if (code == HttpStatus.SC_OK) {
String json = EntityUtils.toString(response.getEntity());
handleResult(json);
}
} catch (IOException e) {
Log.e("TAG", "Failed to execute response", e);
}
}
private void handleResult(String json) {
try {
JSONObject jObject = new JSONObject(json);//your response is not an array
JSONArray content = jObject.getJSONArray("city")
final int count = content.length();
for (int i = 0; i < count; i++) {
JSONObject city = content.getJSONObject(i);
Log.d("TAG", city.getString("ct_id"));
}
} catch (JSONException e) {
Log.e("TAG", "Failed to obtain json", e);
}
}
I'm using mvc 4 web api for getting JSONArray and consume it in android application but this error is occurred:
of type java.lang.String cannot be converted to JSONArray
this is JSON:
[{
"FileType": {
"FileTypeId": 1,
"Name": "Estate",
"CodeLength": 5
},
"FileId": 2,
"FileTypeId": 1,
"FileNumber": "12345"
}, {
"FileType": {
"FileTypeId": 1,
"Name": "Estate",
"CodeLength": 5
},
"FileId": 3,
"FileTypeId": 1,
"FileNumber": "12345"
}]
and this is my code:
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONArray jArray = new JSONArray(jsonStr); //<=== Error is Here
JSONArray Files = null;
// Getting JSON Array node
Files = jArray;
// looping through All Files
for (int i = 0; i < Files.length(); i++) {
JSONObject c = Files.getJSONObject(i);
String FileNumber = c.getString(TAG_FileNumber);
// FileType node is JSON Object
JSONObject FileType = c.getJSONObject(TAG_FileType);
String Name = FileType.getString(TAG_FileType_Name);
// tmp hashmap for single contact
HashMap<String, String> file = new HashMap<String, String>();
// adding each child node to HashMap key => value
file.put(TAG_FileNumber, FileNumber);
file.put(TAG_FileType_Name, Name);
// adding file to file list
FileList.add(file);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
Maybe I am not the best person to help you due to lack of knowledge in the specific field you ask answer for BUT:
I looked it up here: http://www.json.org/javadoc/org/json/JSONArray.html#JSONArray(java.lang.String)
and one of the constructors takes String as a parameter and it says:
Parameters: source - A string that begins with [ (left bracket) and ends with ] (right bracket).
Try to enter a string of that format!
Add these lines into your json strings as
{
"array":
// your json
}
and change this line
JSONArray jArray = new JSONArray(jsonStr);
to
JSONObject jObj = new JSONObject(jsonStr);
JSONArray jArray= jObj.getJSONArray("array");