Android parse json force stopped - android

I am parsing a json url: http://www.json-generator.com/api/json/get/bQmwsOmYeq?indent=2 but I failed to make it happen. I am getting an error. What's wrong with this code?
public void parseJsonResponse(String result) {
Log.i(TAG, result);
pageCount++;
try {
JSONObject json = new JSONObject(result);
JSONArray jArray = json.getJSONArray("name");
for (int i = 0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
CountryInfor country = new CountryInfor();
country.setId(jObject.getString("id"));
country.setName(jObject.getString("name"));
countries.add(country);
}
adapter.notifyDataSetChanged();
if (dialog != null) {
dialog.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
}
}

Replace
JSONObject json = new JSONObject(result);
JSONArray jArray = json.getJSONArray("name");
these two lines by
JSONArray jArray = new JSONArray(result);
Also change
country.setId(jObject.getString("id"));
by
country.setId(jObject.getInt("id") + "");
Because id is of type int not a String.
And it will work fine.
You are getting response like
[
{
"id": ​1,
"name": "Vietnam"
},
{
"id": ​2,
"name": "China"
},
{
"id": ​3,
"name": "USA"
},
{
"id": ​4,
"name": "England"
},
{
"id": ​10,
"name": "Russia"
}
]
So the response is JSONArray and not JSONObject.
Hope it'll help.
Edit
#Override
protected String doInBackground(Void... params) {
// call load JSON from url method
if(loadJSON(this.url) != null) {
return loadJSON(this.url).toString();
}
Log.d("LoadJSONFromUrl", "Failed to get JSONObject.");
return null;
}
You are getting JSONObject null, so the error is.
- You should know what is NullPointerException

the issue is with this line
JSONArray jArray = json.getJSONArray("name");
There is no array with name name. it is failing here. Correct this part to obtain the array properly. Rest looks fine.

Related

How to get json object and array values?

How to parse JSON values in this format? I want to get the details of the data element but inside data there are 'dates' and inside dates there is array containing two more elements. I want to get all the dates first inside data and then within these dates I want all the information within these dates. How can I achieve this? Please Help. I tried with below code but it hasn't worked
try {
JSONObject jsonObject = new JSONObject("data");
JSONArray jsonArray =jsonObject.getJSONArray(String.valueof(cuurentdate));
JSONArray session;
for (int i = 0; i < jsonArray.length() - 1; i++) {
jsonObject = jsonArray.getJSONObject(i);
session= jsonObject.getJSONArray("session");
Log.d("MyLog", session + "");
}
} catch (JSONException e) {
e.printStackTrace();
}
Following is the format
{
"status": 1,
"status_code": 200,
"data": {
"2018-02-11": [
{
"session": "01:00 AM",
"place": true
},
{
"session": "02:00 AM",
"place": true
}
],
"2018-02-12": [
{
"session": "01:00 AM",
"place": true
},
{
"session": "02:00 AM",
"place": true
}
]
}
}
You just need to pass the response string to the method. You can try this:
private void jsonParsing(String jsonString) {
// String jsonString = "{ \"status\": 1, \"status_code\": 200, \"data\": { \"2018-02-11\": [ { \"session\": \"01:00 AM\", \"place\": true }, { \"session\": \"02:00 AM\", \"place\": true } ], \"2018-02-12\": [ { \"session\": \"01:00 AM\", \"place\": true }, { \"session\": \"02:00 AM\", \"place\": true } ] } }";
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject dataObj = jsonObject.getJSONObject("data");
Iterator<String> iter = dataObj.keys();
Log.e(TAG, "jsonParsing: "+iter );
while (iter.hasNext()) {
String key = iter.next();
JSONArray datesArray = dataObj.getJSONArray(key);
ArrayList<String> sessions = new ArrayList<String>();
for (int i = 0; i < datesArray.length(); i++) {
JSONObject datesObject = datesArray.getJSONObject(i);
sessions.add(datesObject.getString("session"));
}
Log.d("MyLog", sessions + "");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
(1) get JSONObject of Main json
JSONObject objMain = new JSONObject("your json string");
(2)get JSONObject of "data" from main json
JSONObject jsonData = objMain.getJSONObject("data")
(3) get all keys (dates) from object "data"
Iterator<String> iter = jsonData.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
JSONArray arrayDate = objData.getJSONArray(key)
for (i = 0; i < arrayDate.length(); i++) {
JSONObject objDate = arrayDate.getJSONObject(i)
Log.d("#session :", "" + objDate.getString("session"))
Log.d("#place :", "" + objDate.getBoolean("place"))
}
} catch (JSONException e) {
// Something went wrong!
}
}
try this one code
IN THIS CODE jsonMstObject IS TEMP OBJECT YOU HAVE TO USE YOUR API RESPONSE JSONobject INSTEAD OF jsonMstObject
try {
JSONObject jsonMstObject = new JSONObject("{"status":1,"status_code":200,"data":{"2018-02-11":[{"session":"01:00 AM","place":true},{"session":"02:00 AM","place":true}],"2018-02-12":[{"session":"01:00 AM","place":true},{"session":"02:00 AM","place":true}]}}");
JSONObject jsonObject = jsonMstObject.getJSONObject("data");
JSONArray jsonArray =jsonObject.getJSONArray(String.valueof(cuurentdate));
ArrayList<String> arrSession = new ArrayList<String>();
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
arrSession.add(jsonObject.getString("session"));
}
Log.d("MyLog", arrSession + "");
} catch (JSONException e) {
e.printStackTrace();
}
in this code arrSession is your session string array
Ex. you passed cuurentdate = "2018-02-11" then you recived result like
[01:00 AM, 02:00 AM]
Note: this code is worked based on your cuurentdate param. This is code for get static date array from data and create String Array.

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 get json string from array inside json array

Initial JSON
{
"data": [
{
"request": [
[
{
"name": "John""email": "John#gmail.com"
}
],
[
"name": "William""email": "William#gmail.com"
]
]
}
]
}
Corrected JSON as it was not passing through JSONLint
{
"data": [
{
"request": [
{
"name": "John",
"email": "John#gmail.com"
},
{
"name": "William",
"email": "William#gmail.com"
}
]
}
]
}
How to extract an array of JSON inside JSON array.I got error message as
json array cannot be converted into JSON Object.
Following code will help to parse your Json:
try {
JSONObject jsonData = new JSONObject(jsonObject);
JSONArray dataJsonArray = jsonData.getJSONArray("data");
JSONArray jsonRequest = dataJsonArray.getJSONObject(0)
.getJSONArray("request");
JSONArray mRequestChildJson = jsonRequest.getJSONArray(0);
JSONObject innerJson = mRequestChildJson.getJSONObject(0);
LogHandler.e("TAG",
"mRequestChildJson" + innerJson.toString());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
don't forgot to add check of has Key and size of array.
may be you're on right track but casting it in object
JSONArray JArray = jObject.getJSONArray("data");
try {
String str = result.toString();
System.out.println("prov-request -->"+str);
JSONObject json=new JSONObject(str);
JSONArray jsonarray = json.getJSONArray("data");
for(int i=0;i<jsonarray.length();i++){
JSONObject jsonnew=jsonarray.getJSONObject(i);
JSONArray jsonarrayROW = jsonnew.getJSONArray("request");
for(int j=0;j<jsonarrayROW.length();j++){
JSONObject jsonObject=jsonarrayROW.getJSONObject(j);
date.add(jsonObject.getString("name"));
from.add(jsonObject.getString("email"));
}
} catch (JSONException e) {
e.printStackTrace();
}

How to parse json with android

how to get json data with android
my json like this:
[
{
"meta": {
"next_id": 30
}
},
{
"data": [
{
"category_id": "2",
"name": "Anniversary Facebook Status",
"count": "53"
},
{
"category_id": "4",
"name": "April Fool Status",
"count": "16"
},
{
"category_id": "79",
"name": "Wise Facebook Status",
"count": "90"
}
]
}
]
My code
JSONObject jsonobject = JSONfunctions.getJSONfromURL("URL");
JSONArray jsonarray = jsonobject.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
Log.i("ID", jsonobject.getString("category_id"));
Log.i("Name", jsonobject.getString("name"));
}
i want get "data" array.
please help if anybody know:
Thank You.
Try this.
JSONArray total_array = new JSONArray(string json);
JSONArray data_array = total_array.getJSONObject(1).getJSONArray("data");
for(int i = 0; i < data_array.length(); i++){
JSONObject json_data = data_array.getJSONObject(i);
String category_id = json_data.getString("category_id");
}
Probably this may help you :
JSONArray jsonArray;
try {
jsonArray = new JSONArray("YOUR JSON DATA");
Log.v("MAIN ACTIVITY", "JSON OBJECT :"+jsonArray.getJSONObject(0).getJSONObject("meta").getString("next_id"));
JSONArray dArray = jsonArray.getJSONObject(1).getJSONArray("data");
for(int i=0;i<dArray.length();i++)
{
JSONObject jsonObject = dArray.getJSONObject(i);
Log.v("MAIN ACTIVITY", "JSON DATA :"+jsonObject.getString("category_id"));
Log.v("MAIN ACTIVITY", "JSON DATA :"+jsonObject.getString("name"));
Log.v("MAIN ACTIVITY", "JSON DATA :"+jsonObject.getString("count"));
}
}
catch (JSONException e1) {
e1.printStackTrace();
}
to get json array
JSONArray jsonArray = new JSONArray(jsonStr);
JSONArray dataArray= jsonArray.getJSONObject(1).getJSONArray("data");
for(int i=0;i<dataArray.length();i++){
JSONObject json_data = dataArray.getJSONObject(i);
String category_id = json_data.getString("category_id");
String name = json_data.getString("name");
String count = json_data.getString("count");
}
For more info see Android JSON Parsing Tutorial
Look into the Gson library by Google. It's easier than parsing the fields manually with the included JSON lab.

How to parse JSON Array inside another JSON Array in Android

Please, please help me..
I am working on a project and I am getting data from web-services in JSON format. I am trying to parse it but, I am unable to do it. I have this json-data-
{
"response": {
"status": {
"code": "1",
"message": "sucess",
"user_id": "1"
},
"foods": [
{
"char": "A",
"content": [
{
"food_name": "add Malt"
},
{
"food_name": "a la mode"
},
{
"food_name": "Almonds"
}
]
},
{
"char": "Z",
"content": [
{
"food_name": "Zebra Cakes"
},
{
"food_name": "Zucchini, Baby"
},
{
"food_name": "zxc"
}
]
}
]
}
}
From here I am successfully able to get "foods" Array but I am getting stuck when I am trying to get "content" array and food_name data.
I am using this code but I did not get any solution, please check this snip code.
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("method","eat_tracking_details"));
nameValuePairs.add(new BasicNameValuePair("uid",userid));
// getting JSON string from URL
JSONObject json = jsonParser.makeHttpRequest(JSONParser.urlname,"GET", nameValuePairs);
//System.out.println("****json*"+json);
if (json != null) {
try {
JSONObject response = json.getJSONObject("response");
JSONObject status = response.getJSONObject("status");
code = status.getString("code");
JSONArray FoodArray = response.getJSONArray("foods");
for (int i = 0; i < FoodArray.length(); i++) {
String character = FoodArray.getJSONObject(i).getString("char");
System.out.println("*****character****************"+character);
JSONArray FoodNameArray = new JSONArray(FoodArray.getJSONObject(i).getString("content"));
System.out.println("====================///////////"+FoodNameArray);
for (int j = 0; j <FoodNameArray.length(); j++) {
String Foodname = FoodArray.getJSONObject(j).getString("food_name");
System.out.println("#############"+Foodname);
}
}
} catch (JSONException e) {
// TODO: handle exception
}
}
Check this url for web-service response-
WEB-SERVICE URL
You need to replace your respective part of code with this code:
for (int j = 0; j < FoodNameArray.length(); j++) {
String Foodname = FoodNameArray.getJSONObject(j).getString("food_name");
System.out.println("#############" + Foodname);
}
I believe the best approach would use of GSON library (http://code.google.com/p/google-gson/) . In that case you just have to make your model classes and don't worry about the parsing logic.

Categories

Resources