Related
This question already has answers here:
how to parse JSONArray in android
(3 answers)
Closed 4 years ago.
I have a code where i should pass an static user id for authentication and then fetch the JSON response from the URL and display it in listview. But i get an error that says "JSON Parsing error: No value in (JSON array)". Please help
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "url";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
List<NameValuePair> list=new ArrayList<>();
list.add(new BasicNameValuePair("user_id", "2"));
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
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("promotion_lists");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String promotion_id = c.getString("promotion_id");
String promotion_title = c.getString("promotion_title");
String promotion_description = c.getString("promotion_description");
//
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("promotion_id", promotion_id);
contact.put("promotion_title", promotion_title);
contact.put("promotion_description", promotion_description);
// 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;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Log.e("SignUpRsp", String.valueOf(result));
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[]{"promotion_id", "promotion_title",
"promotion_description"}, new int[]{R.id.promotion_id,
R.id.promotion_title, R.id.promotion_desc});
lv.setAdapter(adapter);
}
}
public String PostData(String[] valuse) {
String s="";
try
{
HttpClient httpClient=new DefaultHttpClient();
HttpPost httpPost=new HttpPost("url");
List<NameValuePair> list=new ArrayList<>();
list.add(new BasicNameValuePair("user_id", "value"));
httpPost.setEntity(new UrlEncodedFormEntity(list));
HttpResponse httpResponse= httpClient.execute(httpPost);
HttpEntity httpEntity=httpResponse.getEntity();
s= readResponse(httpResponse);
}
catch(Exception exception) {}
return s;
}
public String readResponse(HttpResponse res) {
InputStream is=null;
String return_text="";
try {
is=res.getEntity().getContent();
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(is));
String line="";
StringBuffer sb=new StringBuffer();
while ((line=bufferedReader.readLine())!=null)
{
sb.append(line);
}
return_text=sb.toString();
} catch (Exception e)
{
}
return return_text;
}
}
JSON Response:
{
"status": "1",
"message": "Ok",
"promotion_lists": [
{
"promotion_id": "3",
"promotion_image_name": "1.jpg",
"promotion_image_url": "url.jpg",
"promotion_title": "winner",
"promotion_description": "good\ngold\nred",
"admin_status": "1",
"promotion_status": "1",
"promotion_status_description": "Live"
},
]
}
Your JSON parsing is correct
You need to parse your JSON if your response status response code is 1
SAMPLE CODE
Try this
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// check here of your status of response
// is status is 0 USER NOT FOUND
if(jsonObj.getString("status").equals("0")){
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, jsonObj.getString("message"), Toast.LENGTH_SHORT).show();
}
});
// is status is 1 PARSE YOUR JSON
}else {
JSONArray contacts = jsonObj.getJSONArray("promotion_lists");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String promotion_id = c.getString("promotion_id");
String promotion_title = c.getString("promotion_title");
String promotion_description = c.getString("promotion_description");
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("promotion_id", promotion_id);
contact.put("promotion_title", promotion_title);
contact.put("promotion_description", promotion_description);
// 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();
}
});
}
}
Your json also has an issue, can you try with this output json. Last comma(,) in an array is not required.
{
"status": "1",
"message": "Ok",
"promotion_lists": [
{
"promotion_id": "3",
"promotion_image_name": "1.jpg",
"promotion_image_url": "url.jpg",
"promotion_title": "winner",
"promotion_description": "good\ngold\nred",
"admin_status": "1",
"promotion_status": "1",
"promotion_status_description": "Live"
}
]
}
JSONArray throw error because promotion_lists with a item but has needless comma.
{
"status": "1",
"message": "Ok",
"promotion_lists": [
{
"promotion_id": "3",
"promotion_image_name": "1.jpg",
"promotion_image_url": "url.jpg",
"promotion_title": "winner",
"promotion_description": "good\ngold\nred",
"admin_status": "1",
"promotion_status": "1",
"promotion_status_description": "Live"
}
]
}
Your JSON parse looks fine. The issue is with the your JSON response. It is not a valid JSON Response as there is a unnecessary comma after the JSON Array "promotion_lists". Try removing the comma.
You can use this solution
public class GetContacts extends AsyncTask<String, Void, String> {
protected void onPreExecute() {
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... arg0) {
try {
URL url = new URL(URL HERE);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);
JSONObject postDataParams = new JSONObject();
postDataParams.put("user_id", user_id);
Log.i("JSON", postDataParams.toString());
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
//os.writeBytes(URLEncoder.encode(jsonParam.toString(), "UTF-8"));
os.writeBytes(postDataParams.toString());
os.flush();
os.close();
Log.i("STATUS", String.valueOf(conn.getResponseCode()));
Log.i("MSG", conn.getResponseMessage());
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new
InputStreamReader(
conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
conn.disconnect();
return sb.toString();
} else {
conn.disconnect();
return new String("false : " + responseCode);
}
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String jsonStr) {
try {
pDialog();
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("promotion_lists");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String promotion_id = c.getString("promotion_id");
String promotion_title = c.getString("promotion_title");
String promotion_description = c.getString("promotion_description");
//
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("promotion_id", promotion_id);
contact.put("promotion_title", promotion_title);
contact.put("promotion_description", promotion_description);
// adding contact to contact list
contactList.add(contact);
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[]{"promotion_id", "promotion_title",
"promotion_description"}, new int[]{R.id.promotion_id,
R.id.promotion_title, R.id.promotion_desc});
lv.setAdapter(adapter);
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
} else {
Log.e(TAG, "Couldn't get json from server.");
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
One more thing you dont need to use runOnUiThread in Asynctask because
both are helper threads , which are used to Update UI,you dont have to
use runOnUIThread in it , just simple show toast without using it, it
will show it , read the documentation
https://developer.android.com/guide/components/processes-and-threads
I'm trying to parse this JSON:
{
"data": [{
"name": "Griya Legita",
"is_broken": false,
"is_repaired": false,
"is_ok": true,
"asset_parent": null
},
{
"name": "4th Floor",
"is_broken": true,
"is_repaired": false,
"is_ok": false,
"asset_parent": {
"name": "Buni Building",
"is_broken": true,
"is_repaired": false,
"is_ok": false
}
}]
}
This JSON has a JSON object in a JSON array. But when I call the JSON object it says that it cannot be converted.
This is the code that I've tried:
class daftarAset extends AsyncTask < String, String, String > {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("LOADING...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String...params) {
String link_url = "https://example.com/api/assets";
HttpHandler sh = new HttpHandler();
String json = sh.makeServiceCall(link_url);
Log.e(TAG, "Response from url: " + json);
if (json != null) {
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray data = jsonObject.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
JSONObject ar = data.getJSONObject(i);
String aset = ar.getString("name");
JSONObject parent = ar.getJSONObject("asset_parent");
String nama = parent.getString("name");
HashMap map = new HashMap();
map.put(in_aset, aset);
map.put(in_ruang, nama);
data_map.add(map);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity().getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
list = (ListView) getView().findViewById(R.id.baik_list);
adapter = new AssetsAdapter(getActivity(), data_map);
list.setAdapter(adapter);
setListViewHeightBasedOnChildren(list);
}
});
}
return null;
}
#Override
protected void onPostExecute(String s) {
pDialog.dismiss();
}
I don't know what's gone wrong in my code. I'm following this tutorial and I feel like it must be correct but it has an error because the JSON cannot be converted.
This is my error:
W/System.err: org.json.JSONException: Value null at asset_parent of type org.json.JSONObject$1 cannot be converted to JSONObject
at org.json.JSON.typeMismatch(JSON.java:100)
at org.json.JSONObject.getJSONObject(JSONObject.java:613)
at com.mqa.android.monas.Fragment.BaikFragment$daftarAset.doInBackground(BaikFragment.java:188)
at com.mqa.android.monas.Fragment.BaikFragment$daftarAset.doInBackground(BaikFragment.java:162)
at android.os.AsyncTask$2.call(AsyncTask.java:292)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
First make sure JSONObject contains asset_parent key and corresponding key value is not null. Then retrieve value from JSONObject.
Use this code :
JSONObject jsonObject = new JSONObject(json);
JSONArray data = jsonObject.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
JSONObject ar = data.getJSONObject(i);
String aset = ar.getString("name");
HashMap map = new HashMap();
map.put(in_aset, aset);
if(ar.has("asset_parent") && !ar.isNull("asset_parent") ){
JSONObject parent = ar.getJSONObject("asset_parent");
String name = parent.getString("name");
map.put(in_ruang, name );
}else{
map.put(in_ruang, null );
}
Log.i("Test", "Map: " + map.toString());
data_map.add(map);
................
.............
}
Hope it will solve your problem.
Let me know if your problem is solved.
Try This
if(mJsonObject.has("Data") && !mJsonObject.isNull("Data") ) {
// code here
}
Make a check whether the object is available or not like below
if(ar.optJSONObject("asset_parent")) {
if(ar.getJSONObject("asset_parent") != null) {
//process the object
}
}
public void get_user_details(){
StringRequest stringRequest = new StringRequest( Request.Method.GET,User_Details_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
Log.e("Response",""+response);
JSONObject obj = new JSONObject(response);
JSONArray user_holder = obj.getJSONArray("User_holder");
JSONObject user = user_holder.getJSONObject(0);
user_id=user.getString("id");
user_name=user.getString("user_name");
user_password=user.getString("user_password");
user_emailid=user.getString("user_email");
PreferenceUtils.saveEmail(user_emailid,Register_Page.this);
PreferenceUtils.saveUsername(user_name,Register_Page.this);
PreferenceUtils.savePassword(user_password,Register_Page.this);
PreferenceUtils.saveUserid(user_id, Register_Page.this);
PreferenceUtils.saveLocalValue(localValue, Register_Page.this);
sharedPreferences.writeLginStastu(true);
if(PreferenceUtils.getEmail(Register_Page.this)!=null || !PreferenceUtils.getEmail(Register_Page.this).equals("")){
startActivity(new Intent(Register_Page.this, CongoCoin.class));
sharedPreferences.writeLginStastu(true);
finish();
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("User_json",""+e.toString());
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
I am parsing json value into gridView, but somehow its not showing any value in gridView, i am confused in json code as i think i am missing something in this code..kindly check :
private void getData() {
//Showing a progress dialog while our app fetches the data from url
final ProgressDialog loading = ProgressDialog.show(this, "Please wait...", "Fetching data...", false, false);
String DATA_URL = "http://........nList";
StringRequest stringRequest = new StringRequest(Request.Method.POST, DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Toast.makeText(PMPigeonListingActivity.this,response,Toast.LENGTH_LONG).show();
loading.dismiss();
try {
JSONArray json = new JSONArray(response);
for (int i = 0; i < json.length(); i++) {
//Creating a json object of the current index
JSONObject obj = null;
try {
//getting json object from current index
obj = json.getJSONObject(i);
//getting image url and title from json object
pid.add(obj.getInt(String.valueOf(TAG_PID)));
pname.add(obj.getString(TAG_PNAME));
pdetails.add(obj.getString(TAG_PDETAILS));
pmobile.add(obj.getString(TAG_MOBILE));
pemail.add(obj.getString(TAG_EMAIL));
images.add(obj.getString(TAG_IMAGE_URL));
names.add(obj.getString(TAG_NAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
//Creating GridViewAdapter Object
PMPigeonListAdapter pmpigeonlistadapter = new PMPigeonListAdapter(getApplicationContext(), images, names, pid, pdetails, pmobile, pemail, pname);
//Adding adapter to gridview
pmpigeonlistadapter.notifyDataSetChanged();
gridView.setAdapter(pmpigeonlistadapter);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(PMPigeonListingActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("country", PostCountry);
params.put("strain", PostStrain);
params.put("distance", PostDistance);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
this is my json output:
{
"status_code": 200,
"status": "OK",
"status_message": "Success",
"pigeon_list": [
{
"id": "1",
"pigeon_name": "sofiee",
"auth_token": "58809c7129a5a",
"country_code": "AE",
"strain_id": "75",
"distance": "3",
"pigeon_price": "50.00",
"pigeon_details": "One of the best ",
"image": "http:.98a8ac5.jpeg",
"pedigree_image": "http://...1.jpeg",...
"status": "",
"created": "2017-01-19 16:52:14",
"updated": "0000-00-00 00:00:00",
"strain_name": "Janssen/gaston wowers ",
"usr_mobile": "+971/505040009",
"usr_image": "http://....19a.jpeg",
"usr_email": "...edo#gmail.com"
},
I am getting response in toast also, only json problem is thr ...
this is the php code:
public function searchPigeonList()
{
$data = (array)$this->request->input('json_decode');
$returnArr = $this->resp_arr;
$returnArr['pigeon_list'] = array();
$conn = ConnectionManager::get('default');
$query = "SELECT `pg`.*,`ps`.name as strain_name,`us`.mobile as usr_mobile,`us`.image as usr_image,`us`.email as usr_email FROM
`pigeons` as `pg` INNER JOIN `users` as `us` ON `pg`.`auth_token` = `us`.`uniq_id` INNER JOIN `pigeon_strain` as `ps` ON `ps`.`id` = `pg`.`strain_id` ";
// $query .= "WHERE `pg`.`country_code` = '".$data['country_code']."' ";
$cnt_cd = $data['country_code'];
$str_id = $data['strain_id'];
$dst = $data['distance'];
$conditions = array();
if($cnt_cd !="") {
$conditions[] = "`pg`.country_code='$cnt_cd'";
}
if($str_id !="") {
$conditions[] = "`pg`.strain_id='$str_id'";
}
if($dst !="") {
$conditions[] = "`pg`.distance='$dst'";
}
if (count($conditions) > 0) {
$query .= " WHERE " . implode(' AND ', $conditions);
$query .= " AND `pg`.status='approved'";
}
//echo $query;exit;
$stmt = $conn->execute($query);
$returnArr['status_code'] = 200;
$returnArr['status'] = "OK";
$returnArr['status_message'] = "Success";
$returnArr['pigeon_list'] = $stmt ->fetchAll('assoc');
if ($this->request->is('post')) {
echo json_encode($returnArr);
exit;
}
}
try {
JSONArray json = new JSONObject(response).getJSONArray("pigeon_list");
for (int i = 0; i < json.length(); i++) {
JSONObject obj = null;
try {
obj = json.getJSONObject(i);
pid.add(obj.getInt("id"));
pname.add(obj.getString("pigeon_name"));
pdetails.add(obj.getString("pigeon_details"));
pmobile.add(obj.getString("usr_mobile"));
pemail.add(obj.getString("usr_email"));
images.add(obj.getString("usr_image"));
names.add(obj.getString("pigeon_name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}catch(JSONException je){
je.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
try replacing with
Try this.
public void onResponse(String response) {
//Toast.makeText(PMPigeonListingActivity.this,response,Toast.LENGTH_LONG).show();
loading.dismiss();
try {
JSONObject responseObject=new JSONObject(response);
JSONArray json = responseObject.getJSONArray("pigeon_list");
for (int i = 0; i < json.length(); i++) {
//Creating a json object of the current index
JSONObject obj = null;
try {
//getting json object from current index
obj = json.getJSONObject(i);
//getting image url and title from json object
pid.add(obj.getInt(String.valueOf(TAG_PID)));
pname.add(obj.getString(TAG_PNAME));
pdetails.add(obj.getString(TAG_PDETAILS));
pmobile.add(obj.getString(TAG_MOBILE));
pemail.add(obj.getString(TAG_EMAIL));
images.add(obj.getString(TAG_IMAGE_URL));
names.add(obj.getString(TAG_NAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
//Creating GridViewAdapter Object
PMPigeonListAdapter pmpigeonlistadapter = new PMPigeonListAdapter(getApplicationContext(), images, names, pid, pdetails, pmobile, pemail, pname);
//Adding adapter to gridview
pmpigeonlistadapter.notifyDataSetChanged();
gridView.setAdapter(pmpigeonlistadapter);
}
hi guys i don't know why but i get this error: JSONArray cannot be converted to JSONObject.
I show you my code!I hope that you can help me! thanks in advance everybody!
Sorry, but i am new to JSON.
MAIN ACTIVITY:
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = " http://v1.tvguideapi.com/programs?channels[]=2161&channels[]=2162&start=1484598600&stop=1484605799";
//private static String url = "http://api.androidhive.info/contacts/";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
//JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("programs");
// JSONArray contacts = jsonObj.getJSONArray("contacts");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
/* String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String address = c.getString("address");
String gender = c.getString("gender");
// Phone node is JSON Object
JSONObject phone = c.getJSONObject("phone");
String mobile = phone.getString("mobile");
String home = phone.getString("home");
String office = phone.getString("office");*/
String title=c.getString("title");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
/* contact.put("id", id);
contact.put("name", name);
contact.put("email", email);
contact.put("mobile", mobile);*/
contact.put("title",title);
// 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;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
/* MainActivity.this, contactList,
R.layout.list_item, new String[]{"name", "email",
"mobile"}, new int[]{R.id.name,
R.id.email, R.id.mobile});*/
MainActivity.this, contactList,
R.layout.list_item, new String[]{"title"}, new int[]{R.id.title});
lv.setAdapter(adapter);
}
}
}
JSON:
[
{
"id": "18879971",
"start": "2017-01-16 20:20:00",
"stop": "2017-01-16 22:30:00",
"lang": "",
"title": "Il Collegio</td>",
"subtitle": "",
"description": "",
"category": "",
"channel_id": "2162",
"icon": null,
"ts_start": 1484598000,
"ts_stop": 1484605800
},
{
"id": "18879856",
"start": "2017-01-16 20:25:00",
"stop": "2017-01-16 22:40:00",
"lang": "",
"title": "I Bastardi di Pizzofalcone",
"subtitle": "",
"description": "Ep.3 - In un fatiscente condominio di Pizzofalcone viene rinvenuto il cadavere di una camariera. Le indagini della squadra portano al marito della donna, ma per Lojacono il caso si complica ulteriormente.",
"category": "",
"channel_id": "2161",
"icon": null,
"ts_start": 1484598300,
"ts_stop": 1484606400
}
]
You should use you have Json Array.
you have [{ },{}] format Here [] shows JsonArray and {} this is json object.
you can have Json array loop through array and get Json object.
JSONArray contacts = new JSONArray(jsonStr);
Instead of using
JSONObject jsonObj = new JSONObject(jsonStr);
Now you can fetch data
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
//Get all required data using c.
String id = c.getString("id");
String name = c.getString("start");
}
I need to parse JSON file with multiple arrays.
Array is in format:
{
"List": {
"Something": [
{
"Name": "John",
"phone": "test"
}
]
"SomethingElse": [
{
"Name": "Smith",
"phone": "test"
}
]
}
}
Problem is that i don't know what wold be next array name. It is possible to parse data from all arrays without name of it and without changing structure of it?
Thanks.
JSON
{
"data": {
"current_condition": [
{
"cloudcover": "25",
"humidity": "62",
"observation_time": "04:57 PM",
"precipMM": "0.1",
"pressure": "1025",
"temp_C": "10",
"temp_F": "50",
"visibility": "10",
"weatherCode": "113",
"weatherDesc": [
{
"value": "Clear"
}
]
}
]
}
}
TO GET THE VALUE OF "weatherDesc"
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://api.worldweatheronline.com/free/v1/weather.ashx?q=London&format=json&num_of_days=5&key=8mqumbup9fub7bcjtsxbzxx9");
try {
// Locate the array name in JSON
JSONObject on=jsonobject.getJSONObject("data");
jsonarray = on.getJSONArray("current_condition");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
JSONArray sen1=jsonobject.getJSONArray("weatherDesc");
// Retrive JSON Objects
for(int j=0;j<sen1.length();j++){
jsonobject2 = sen1.getJSONObject(j);
map.put("value0", jsonobject2.getString("value"));
map.put("value1",jsonobject2.getString("value"));
map.put("flag", null);
// Set the JSON Objects into the array
arraylist.add(map);
}
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
try this
I had write a function to iterate JsonObject recursively without knowing keys name.
private void parseJson(JSONObject data) {
if (data != null) {
Iterator<String> it = data.keys();
while (it.hasNext()) {
String key = it.next();
try {
if (data.get(key) instanceof JSONArray) {
JSONArray arry = data.getJSONArray(key);
int size = arry.length();
for (int i = 0; i < size; i++) {
parseJson(arry.getJSONObject(i));
}
} else if (data.get(key) instanceof JSONObject) {
parseJson(data.getJSONObject(key));
} else {
System.out.println("" + key + " : " + data.optString(key));
}
} catch (Throwable e) {
System.out.println("" + key + " : " + data.optString(key));
e.printStackTrace();
}
}
}
}
There is a comma missing in your JSON after the Something value, but apart from that, you can parse it using any JSON parser.