JSON Data Parsing Error the response from server becomes null: Android - android

I am trying to fetch data from the server and then display it into the app.
I have JSON data as,
{"COLUMNS":["TIMEID","BRANCHID","COMPANYID","MON_O","TUE_O","WED_O","THU_O","FRI_O","SAT_O","SUN_O","MON_C","TUE_C","WED_C","THU_C","FRI_C","SAT_C","SUN_C","CREATDATE"],"DATA":[[195,4,4,"09:00","09:00","09:00","09:00","09:00","Closed","Closed","16:30","16:30","16:30","16:30","16:30","Closed","Closed","May, 16 2017 08:16:12"]]}
I have my JAVA class as,
public static final String MON_O = "MON_O";
public static final String TUE_O = "TUE_O";
public static final String WED_O = "WED_O";
public static final String THU_O = "THU_O";
public static final String FRI_O = "FRI_O";
public static final String SAT_O = "SAT_O";
public static final String SUN_O = "SUN_O";
public static final String MON_C = "MON_C";
public static final String TUE_C = "TUE_C";
public static final String WED_C = "WED_C";
public static final String THU_C = "THU_C";
public static final String FRI_C = "FRI_C";
public static final String SAT_C = "SAT_C";
public static final String SUN_C = "SUN_C";
public static final String JSON_ARRAY = "COLUMNS";
private void getData() {
String url = context.getString(site_url)+"branch_time.cfc?method=branchtime&branchid=" +dBranchID;
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);
}
private void showJSON(String response) {
String name = "";
try {
JSONObject jsonObject = new JSONObject(response);
Log.d("TAG", jsonObject.toString());
JSONArray result = jsonObject.getJSONArray(JSON_ARRAY);
Log.d("TAG", result.toString());
JSONObject companyData = result.getJSONObject(0);
name = companyData.getString(MON_O);
Log.e(name,"datadtadattadtatadtat");
} catch (JSONException e) {
e.printStackTrace();
}
timeStatus.setText(name);
}
When I am triying to log the response from the server, I could see that only the COLUMNS value is there where as the DATA is null.
Also, I am getting an error as below,
System.err: org.json.JSONException: Value TIMEID at 0 of type java.lang.String cannot be converted to JSONObject
Why would I get the DATA values from the server as null and how am I suppose to fix the error?
I have referred the links: org.json.JSONException: Value of type java.lang.String cannot be converted to JSONArray
Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
However, these do not seem to help in my case. Please can anyone help?

Try this.....
JSONParser jsonParser = new JSONParser();
jsonObject = jsonParser.getJSONFromUrl(url);
try {
user1 = jsonObject.getJSONArray("COLUMNS");
for (int i = 0; i < user1.length(); i++) {
String value = (String) user1.get(i);
getList.add(value.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}

I observe your json response, i think whatever you are having in column json array there are nothing having string which you are getting thats why you are getting error,
In your response nothing having key value pair so its easy to get String.
so you should getString() instead of getJsonObject()
private void showJSON(String response) {
String name = "";
try {
JSONObject jsonObject = new JSONObject(response);
Log.d("TAG", jsonObject.toString());
JSONArray result = jsonObject.getJSONArray(JSON_ARRAY);
Log.d("TAG", result.toString());
name = result.getString(index);
Log.e(name,"datadtadattadtatadtat");
} catch (JSONException e) {
e.printStackTrace();
}
index is basically json array index you can put it 0 or something and go for loop if you want.

Related

Parse string data to jsonutl class and give me error in return void

public class JsonUtils {
public JsonUtils() throws JSONException {
}
public static Sandwich parseSandwichJson(String json) throws JSONException {
String jsonStr = new String();
JSONArray jsonArray = new JSONArray(jsonStr);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonobject = jsonArray.getJSONObject(i);
String mainName = jsonobject.getString("mainName");
String alsoKnownAs = jsonobject.getString("alsoKnownAs");
String placeOfOrigin = jsonobject.getString("placeOfOrigin");
String description = jsonobject.getString("description");
String image = jsonobject.getString("image");
String ingredients = jsonobject.getString("ingredients");
return ;
}
}
i want to solve the error in return; line and solve the problem
in this i try to get parse json and need to void return
First of all remove return from your for loop and also your method return type is Sandwich change it to void like:
public static void parseSandwichJson(String json) throws JSONException

Value connection of type java.lang.String cannot be converted to JSONObject

String url = Config.DATA_URL+TempItem.toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.GET,url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
}
},
This is the constructor where I parse in my response.
I am a total beginner in android studio and I have no idea how to solve this error. I have read other forums which I tried implementing to no avail. My JSON result is
"result":[
{
"BusinessName":"KachangPuteh",
"AmountTotal":"100‌​",
"RequiredTotal":"2‌​00",
"MaxTotal":"500" ‌​
}
]
}
private void showJSON(String response){
String name="";
String AmountTotal="";
String RequiredTotal = "";
String MaxTotal = "";
try {
JSONObject jsonObject = new JSONObject(response);
String results= jsonObject.getString(Config.JSON_ARRAY);
JSONArray result = new JSONArray(results);
JSONObject stallsData = result.getJSONObject(0);
name = stallsData.getString(Config.KEY_NAME);
AmountTotal = stallsData.getString(Config.KEY_AmountTotal);
MaxTotal = stallsData.getString(Config.KEY_MT);
RequiredTotal = stallsData.getString(Config.KEY_RT);
} catch (JSONException e) {
e.printStackTrace();
Log.e("error ",e.getMessage());
}
Stall.setText("Name:\t"+name+"\nAmountTotal:\t" +AmountTotal+ "\nMaxTotal:\t"+ MaxTotal);
}
This is to change my JSONObject to JSONArray.
Edit:
This is my php file
<?php
if($_SERVER['REQUEST_METHOD']=='GET'){
$id = $_GET['id'];
require_once('conn.php');
$sql = "SELECT * FROM business WHERE BusinessID='".$id."'";
$r = mysqli_query($conn,$sql);
$res = mysqli_fetch_array($r);
$result = array();
array_push($result,array(
"BusinessName"=>$res["BusinessName"],
"AmountTotal"=>$res["AmountTotal"],
"RequiredTotal"=>$res["RequiredTotal"],
"MaxTotal"=>$res["MaxTotal"]
)
$str = json_encode(array("result"=>$result)); $str=str_replace('​','',$str); $str=str_replace('‌','',$str); echo $srt;
echo json_encode(array("result"=>$result));
);
mysqli_close($conn);
}
this is my config file.
public class Config {
public static final String DATA_URL = "http://192.168.1.2/retrieveone.php?id=";
public static final String KEY_NAME = "BusinessName";
public static final String KEY_AmountTotal = "AmountTotal";
public static final String KEY_RT = "RequiredTotal";
public static final String KEY_MT = "MaxTotal";
public static final String JSON_ARRAY = "result";
}
You are parsing data wrongly. Try below code -
JSONArray result = jsonObject.getJSONArray("result");
JSONObject stallsData = result.getJSONObject(0);
Here i am doing some changes in your code .
{"result":[
{
"BusinessName":"KachangPuteh",
"AmountTotal":"100‌​",
"RequiredTotal":"2‌​00",
"MaxTotal":"500" ‌​
} ] }
this will be your actual response.
now i am going to parse it.
` private void showJSON(String response){
String name="";
String AmountTotal="";
String RequiredTotal = "";
String MaxTotal = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray("result"); // this line is new
for(int i=0;i<result.length;i++){
JSONObject stallsData = result.getJSONObject(i);
name = stallsData.getString(Config.KEY_NAME);
AmountTotal = stallsData.getString(Config.KEY_AmountTotal);
MaxTotal = stallsData.getString(Config.KEY_MT);
RequiredTotal = stallsData.getString(Config.KEY_RT);
} catch (JSONException e) {
e.printStackTrace();
Log.e("error ",e.getMessage());
}
}Stall.setText("Name:\t"+name+"\nAmountTotal:\t" +AmountTotal+ "\nMaxTotal:\t"+ MaxTotal);
}
you can write
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray loginNodes = jsonObject.getJSONArray("result");
pDialog.dismiss();
for (int i = 0; i < loginNodes.length(); i++) {
JSONObject jo = loginNodes.getJSONObject(i);
String BusinessName= jo.getString("BusinessName");
String AmountTotal= jo.getString("AmountTotal");
String RequiredTotal= jo.getString("RequiredTotal");
String MaxTotal= jo.getString("MaxTotal");
}
} catch (JSONException e) {
e.printStackTrace();
}

Part of JSON response from server is returning null: Android

I am trying to fetch data from the server and then display it into the app.
I have JSON data as,
{"COLUMNS":["TIMEID","BRANCHID","COMPANYID","MON_O","TUE_O","WED_O","THU_O","FRI_O","SAT_O","SUN_O","MON_C","TUE_C","WED_C","THU_C","FRI_C","SAT_C","SUN_C","CREATDATE"],"DATA":[[195,4,4,"09:00","09:00","09:00","09:00","09:00","Closed","Closed","16:30","16:30","16:30","16:30","16:30","Closed","Closed","May, 16 2017 08:16:12"]]}
When I access the url I get the complete JSON Data but when I am logging the same response from the server, I am not getting the DATA part of the JSON data.
My JAVA class implementation is as,
public static final String MON_O = "MON_O";
public static final String TUE_O = "TUE_O";
public static final String WED_O = "WED_O";
public static final String THU_O = "THU_O";
public static final String FRI_O = "FRI_O";
public static final String SAT_O = "SAT_O";
public static final String SUN_O = "SUN_O";
public static final String MON_C = "MON_C";
public static final String TUE_C = "TUE_C";
public static final String WED_C = "WED_C";
public static final String THU_C = "THU_C";
public static final String FRI_C = "FRI_C";
public static final String SAT_C = "SAT_C";
public static final String SUN_C = "SUN_C";
public static final String JSON_ARRAY = "COLUMNS";
private void getData() {
String url = context.getString(site_url)+"branch_time.cfc?method=branchtime&branchid=" +dBranchID;
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);
}
private void showJSON(String response) {
String name = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(JSON_ARRAY);
Log.d("TAG", result.toString());
name = result.getString(MON_O);
} catch (JSONException e) {
e.printStackTrace();
}
timeStatus.setText(name);
}
I am trying to log the result from the server and getting the below,
["TIMEID","BRANCHID","COMPANYID","MON_O","TUE_O","WED_O","THU_O","FRI_O","SAT_O","SUN_O","MON_C","TUE_C","WED_C","THU_C","FRI_C","SAT_C","SUN_C","CREATDATE"]
The DATA part of the response is null and I can get only the COLUMNS value.
I have no idea why this could happen. Please can anyone help in this?
Maybe it's null because you never did this to get that data correctly
JSONArray companyData = jsonObject.getJSONArray("DATA");
You only got the COLUMNS array, and the data is not within that array.
Also note that data array is an array within an array
Code use for COLUMNS will be:
JSONObject companyData = jsonObject.getJSONArray("COLUMNS");
Code use for DATA will be:
JSONObject companyData = jsonObject.getJSONArray("DATA ");
Please mark my answer useful, if you get you desired solution.

How do I convert an object that contains and arraylist of other objects into JSON for sending to an API - Android

Imagine I have an object - ChildObject. ChildObject has 3 properties. Id, Name, Age.
I also have another object - ParentObject. ParentObject also has 3 properties. Id, Date but the 3rd is ArrayList of ChildObjects Family.
How would I go about converting this into a JSONObject to be able to send it over to a RESTfull WebAPI service.
So far I have failed to find anything that works, and I'm struggling to wrap my head around the problem.
To make it more of a challenge I cant use 3rd party extentions (eg gson etc).
Thanks in advance for your help.
Adding Objects to see if they make it any clearer
ParentObject
public class JobMovementRequestDto {
public String Id_Employee;
public String ActionDate;
public String Id_Terminal;
public String Id_Device;
public ArrayList<JobActivityRequestDto> FromJobs;
public ArrayList<JobActivityRequestDto> ToJobs;
public JobMovementRequestDto(){
}
public JobMovementRequestDto(String idEmployee, String activityDate, String idTerminal, String idDevice, ArrayList<JobActivityRequestDto> fromItems, ArrayList<JobActivityRequestDto> toItems){
this.Id_Employee = idEmployee;
this.ActionDate = activityDate;
this.Id_Terminal = idTerminal;
this.Id_Device = idDevice;
this.FromJobs = fromItems;
this.ToJobs = toItems;
}
public String getIdEmployee() {return this.Id_Employee;}
public String getActivityDate() {return this.ActionDate;}
public String getIdTerminal() {return this.Id_Terminal;}
public String getIdDevice() {return this.Id_Device;}
public ArrayList<JobActivityRequestDto> getFromList() {return this.FromJobs;}
public ArrayList<JobActivityRequestDto> getToLIst() { return this.ToJobs;}
ChildObject
public class JobActivityRequestDto {
public String Id_Job;
public String Id_Batch;
public String Id_ActivityType;
public JobActivityRequestDto()
{
}
public JobActivityRequestDto(String idJob, String idBatch, String idActivityType)
{
this.Id_Job = idJob;
this.Id_Batch = idBatch;
this.Id_ActivityType = idActivityType;
}
public String getIdJob() { return this.Id_Job;}
public String getIdBatch() {return this.Id_Batch;}
public String getIdActivityType() {return this.Id_ActivityType;}
}
Here is your complete solution, Please check.
public void makeJsonObject()
{
try
{
JSONObject parentJsonObject = new JSONObject();
parentJsonObject.put("Id", parentObject.getId());
parentJsonObject.put("Id", parentObject.getDate());
JSONArray childListArr = new JSONArray();
for (int i = 0; i < parentObject.ChildObjectsList().size(); i++)
{
ChildObject childObject = parentObject.ChildObjectsList().get(i);
JSONObject childJsonObject = new JSONObject();
childJsonObject.put("id", childObject.getId());
childJsonObject.put("Name", childObject.getName());
childJsonObject.put("Age", childObject.getAge());
childListArr.put(childJsonObject);
}
parentJsonObject.put("childList", childListArr);
Log.e(TAG, "parentJsonObject=="+parentJsonObject.toString(4));
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
JSONObject fromObject, toObject, parentObject;
JSONArray fromArray, toArray;
JobMovementRequestDto JMRD = new JobMovementRequestDto();
try {
parentObject = new JSONObject();
parentObject.put("Id_Employee", JMRD.getIdEmployee());
parentObject.put("ActionDate", JMRD.getActivityDate());
parentObject.put("Id_Terminal", JMRD.getIdTerminal());
parentObject.put("Id_Device", JMRD.getIdDevice());
fromArray = new JSONArray();
for(JobActivityRequestDto JARD : JMRD.getFromList()){
//Loop your multiple childObjects and add it childArray
fromObject = new JSONObject();
fromObject.put("Id_Job",JARD.getIdJob());
fromObject.put("Id_Batch",JARD.getIdBatch());
fromObject.put("Id_ActivityType",JARD.getIdActivityType());
fromArray.put(fromObject);
}
toArray = new JSONArray();
for(JobActivityRequestDto JARD : JMRD.getToLIst()){
//Loop your multiple childObjects and add it childArray
toObject = new JSONObject();
toObject.put("Id_Job",JARD.getIdJob());
toObject.put("Id_Batch",JARD.getIdBatch());
toObject.put("Id_ActivityType",JARD.getIdActivityType());
toArray.put(toObject);
}
//Finally, Add childArray to ParentObject.
parentObject.put("fromObjects",fromArray);
parentObject.put("toObjects",toArray);
} catch (JSONException e) {
e.printStackTrace();
}
Create a JSON like this and You Can Send This to Your Server. I Hope This Is What You Want Right?

Json Parsing process

I am trying parsing below json in android with below code but I get a error when I do parsing process,How can I parse it? When I do parsing process I get a error in this step final JSONObject jsonm_kurulum = jsonm.getJSONObject("GetkurulumByIDResult");
{
"GetkurulumByIDResult":{
"Astron_test":"OK",
"Note":null,
"aciklama":"ok",
"adres":null,
"bayiID":242,
"bayi_Adi":null,
"bayi_kodu":null,
"descripID":null,
"descriptionCode":null,
"durum":"1",
"form_no":"000008",
"gsm_no":"5493279096",
"kurulum_tarihi":"\/Date(1473022800000+0300)\/",
"muhdendis":"umut",
"ricon_sn":"9922R1608HH0800087",
"signal":"17",
"sira_no":124,
"yetki":"Gökhan Karolo"
}
}
final JSONObject jsonm = new JSONObject(result);
Log.i("#Log", "GetInfogiris");
final JSONObject jsonm_kurulum = jsonm.getJSONObject("GetkurulumByIDResult");
String jsonm_astron = jsonm_kurulum.getString("Astron_test");
String jsonm_note = jsonm_kurulum.getString("Note");
String jsonm_aciklama = jsonm_kurulum.getString("aciklama");
String jsonm_adres = jsonm_kurulum.getString("adres");
String jsonm_bayiId = jsonm_kurulum.getString("bayiID");
String jsonm_bayiAdi = jsonm_kurulum.getString("bayi_Adi");
String jsonm_kodu = jsonm_kurulum.getString("bayi_kodu");
result = {"GetkurulumByIDResult":{"Astron_test":"OK","Note":null,"aciklama":"ok","adres":null,"bayiID":242,"bayi_Adi":null,"bayi_kodu":null,"descripID":null,"descriptionCode":null,"durum":"1","form_no":"000008","gsm_no":"5493279096","kurulum_tarihi":"\/Date(1473022800000+0300)\/","muhdendis":"umut","ricon_sn":"9922R1608HH0800087","signal":"17","sira_no":124,"yetki":"Gökhan Karolo"
}
}
To share optimized way of json parsing, I would suggest you to follow below steps:
Use Gson library (you would not need to parse json response manually but instead it will give you POJO based output and so you would be accessing data using getter and setter methods)
Use this site to create POJO class from JSON http://www.jsonschema2pojo.org/
Try this:
private void parsing(String Url) {
private ServiceRequest mRequest;
mRequest = new ServiceRequest(Activity.this);
mRequest.makeServiceRequest(Url, Request.Method.POST, jsonParams, new ServiceRequest.ServiceListener() {
#Override
public void onCompleteListener(String response) {
String Sstatus = "";
try {
JSONObject jsonm_kurulum = new JSONObject(response);
String jsonm_astron = jsonm_kurulum.getString("Astron_test");
String jsonm_note = jsonm_kurulum.getString("Note");
String jsonm_aciklama = jsonm_kurulum.getString("aciklama");
String jsonm_adres = jsonm_kurulum.getString("adres");
String jsonm_bayiId = jsonm_kurulum.getString("bayiID");
String jsonm_bayiAdi = jsonm_kurulum.getString("bayi_Adi");
String jsonm_kodu = jsonm_kurulum.getString("bayi_kodu");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dialog.dismiss();
}
#Override
public void onErrorListener() {
dialog.dismiss();
}
});
}

Categories

Resources