Retrofit Post: Getting slashes when sending request - android

I am working on Retrofit Post but i am getting slashes () when sending data to post method. Here i need to send the complete json object data to post method, so i converted the json object to String . But when sending slashes are appending to request. I also replaced the slashes to empty string but it is not working. Any one please help me.
code:
private void favouriteadding(String restaurant_id, String restaurant_name, JsonArray Restaurant_info) {
String replac = Restaurant_info.toString(); // jsonarray
replac = replac.replace("[", "")
.replace("]", "")
.trim();
Log.v("Tag_replacestring",""+replac);
ServiceClient serviceClient = ServiceUtil.getServiceClient();
JsonObject userfav = new JsonObject();
userfav.addProperty("user_id", m_sharedPreference.getString("userid", ""));
userfav.addProperty("restaurant_id", restaurant_id);
userfav.addProperty("restaurant_name", restaurant_name);
userfav.addProperty("restaurant_info",replac.replace('\\','"') );
Log.v("Tag_postdata",""+userfav);
serviceClient.list_fav(userfav, listfavcallback);
}
Log:
Tag_replacestring: {"status":"enabled","features":"No Alcohol Available","cuisines":"Hyderabadi","Mughlai","Biryani","Chinese","cost":850.0,"createdAt":"2018-03-08 09:26:13","branch_id":"5aa146ce1d41c86e73e11d79","stats":{},"dishes":"Hyderabadi Dum Biryani","Mutton Biryani}
but getting like this with slashes:
Tag_postdata:
{"user_id":"","restaurant_id":"5aa148051d41c86e73e11d7a","restaurant_name":"Hotel Shadab","restaurant_info":"{\"status\":\"enabled\",\"features\":\"No Alcohol Available\",\"cuisines\":\"Hyderabadi\",\"Mughlai\",\"Biryani\",\"Chinese\",\"cost\":850.0,\"createdAt\":\"2018-03-08 09:26:13\",\"branch_id\":\"5aa146ce1d41c86e73e11d79\"

Related

JSON Parsing on error body (JSON Exception) org . json.JSONException: End of input at character 0

I am getting an error org . json.JSONException: End of input at character 0
This is my Code :-
JSONObject jObjError = new JSONObject(response.errorBody().string());
Log.e("Error","::"+jObjError.getString("error_codes"));
and this is my JSON
{
"errors":{
"provider":["already has an appointment scheduled at this time."]
},
"error_codes":["provider_unavailable"]
}
Can anyone help me with this
The key point here is that you're trying to get a string from an array, not directly from an object. The correct way of parsing this would be:
JSONObject jObjError = new JSONObject(response.errorBody().string());
JSONArray errorArray = jObjError.optJSONArray("error_codes");
for(int i = 0;i<errorArray.size;i++) {
Log.e("Error","::"+errorArray.get(i));
}
If response is your returned JSON, you should pass it directly as parameter is it's of type String
JSONObject jo=new JSONObject(response);
and then do whatever else. because your error messages are customized and returned as json string so this is interpreted as successful request with customized messages.

How to map json data with java class if its changs, sometimes data chages jsonArray to JsonObject in response

I am getting Json Response from the server, And mapping JSON data with Java class.
Here is code.
Gson gsonObj = new Gson();
AppointmentData appointmentData = gsonObj.fromJson(response, AppointmentData.class);
its working fine until response changes sometimes.
Here is response screenshot.
Now look at the response final_slots in response is sometimes as JSON Object and sometimes JSONArray. if final_slots is JSONArray then my Mapping code works, but if its is JSON Object then I have to change the logic. here is my code what I m doing in both cases
JSONObject JsonObjResponse = new JSONObject(response);
JSONObject jsonDataObj = JsonObjResponse.getJSONObject("data");
Object json = new JSONTokener( jsonDataObj.get("final_slots").toString()).nextValue();
/*******************************If response (final_slots) is JsonObject******************************/
if (json instanceof JSONObject) {
JSONObject jsonObj = jsonDataObj.getJSONObject("final_slots");
appointmentData=new AppointmentData();
AppointmentSettingData appointmentSettingData=new AppointmentSettingData();
JsonObjResponse.getString("data");
User userObj=new User();
JSONObject userJsonData= JsonObjResponse.getJSONObject("data").getJSONObject("user");
userObj.pk=userJsonData.getInt("pk");
userObj.unique_id=userJsonData.getString("unique_id");
userObj.fk_role=userJsonData.getInt("fk_role");
userObj.fk_status=userJsonData.getInt("fk_status");
userObj.fk_hospital=userJsonData.getInt("fk_hospital");
userObj.fk_department=userJsonData.getInt("fk_department");
userObj.fk_sub_department=userJsonData.getInt("fk_sub_department");
userObj.user_slug=userJsonData.getString("user_slug");
userObj.first_name=userJsonData.getString("first_name");
userObj.last_name=userJsonData.getString("last_name");
userObj.user_name_en=userJsonData.getString("user_name_en");
userObj.user_name_ar=userJsonData.getString("user_name_ar");
userObj.username=userJsonData.getString("username");
userObj.password=userJsonData.getString("password");
userObj.email=userJsonData.getString("email");
userObj.contact=userJsonData.getString("contact");
// userObj.qualification=userJsonData.getString("qualification");
userObj.mobile=userJsonData.getString("mobile");
userObj.appointment_duration=userJsonData.getInt("appointment_duration");
userObj.registration_date=userJsonData.getString("registration_date");
userObj.activation_code=userJsonData.getString("activation_code");
userObj.email_verified=userJsonData.getInt("email_verified");
userObj.device_token=userJsonData.getString("device_token");
userObj.device_type=userJsonData.getString("device_type");
userObj.device_id=userJsonData.getString("device_id");
userObj.created_at=userJsonData.getString("created_at");
userObj.updated_at=userJsonData.getString("updated_at");
// userObj.created_at=userJsonData.getString("created_by");
userObj.updated_by=userJsonData.getInt("updated_by");
appointmentSettingData.setUser(userObj);
appointmentData.setData(appointmentSettingData);
int i=0;
List<Slots> final_slots=new ArrayList<Slots>();
while(jsonObj.getJSONObject(""+i).has("start") && jsonObj.getJSONObject(""+i).has("end")){
Slots slot=new Slots();
slot.start=jsonObj.getJSONObject(""+i).get("start").toString();
slot.end=jsonObj.getJSONObject(""+i).get("end").toString();
final_slots.add(slot);
appointmentSettingData.setFinal_slots(final_slots);
appointmentData.setData(appointmentSettingData);
i++;
}
totalslots = final_slots.size();
totalslotLines = totalslots / 5;
} else if (json instanceof JSONArray) {
/*******************************If response (final_slots) is JsonArray******************************/
appointmentData = gsonObj.fromJson(response, AppointmentData.class);
totalslots = appointmentData.data.final_slots.size();
totalslotLines = totalslots / 5;
}
Issue:
when in response final_slots comes as json Object. As you can that when it final_slots is as jsonObject then I am getting inside JSON Object by the index as the name of JSON Object(i.e jsonObj.getJSONObject(""+i).get("start")). I am having issue when index is missing (you can see response upload image), because i am getting by the index, assuming that index will not miss in response. but I m fail here.
while(jsonObj.getJSONObject(""+i).has("start") && jsonObj.getJSONObject(""+i).has("end")){
Slots slot=new Slots();
slot.start=jsonObj.getJSONObject(""+i).get("start").toString();
slot.end=jsonObj.getJSONObject(""+i).get("end").toString();
final_slots.add(slot);
appointmentSettingData.setFinal_slots(final_slots);
appointmentData.setData(appointmentSettingData);
i++;
}
what I need:
I want to appointmentData object a compelete object which provide me all response either jsonArray in response or JSonobject in response.
I will be thankful to you for my assistance.

how to get code from json object

I am working with volley for network calling in android. my webservice is send me response object like that
{
   "Code": 200,
   "Message": "Record Found",
   "Result": {
      "deviceid": 10,
      "udid": "359447060356151",
      "businessid": 1,
      "usertype": "Merchant"
   }
}
now i want to read the code and message from this object. but failed to do so. I am using this code for getting this data.
JSONObject jsonObj = new JSONObject(response);
JSONObject userDetails = jsonObj.getJSONObject("Result");
LoginResponse entryObj = new LoginResponse();
entryObj.businessid = userDetails.getInt("businessid");
lr.businessid = entryObj.businessid;
Utilities.businessId = lr.businessid;
help me to read the code from this object. i am not getting the exact solution.
int code = jsonObj.getInt("Code");
String message = jsonObj.getString("Message");
This is how you read code and message.
Hey you can get code string from json using parsing,
JsonObject jsonObj=new jsonObject(response);
String code=jsonObj.optString("Code");
Do like this:
int code = jsonObj.getInt("Code");
String message = jsonObj.getString("Message");

How to retrieve JsonObject data on MVC

I have an android app which send jsonobject to server as follow:
JSONObject jsonParam = new JSONObject();
jsonParam.put("snc", serialClient);
jsonParam.put("code", hashString(pwd + serialClient));
printout = new DataOutputStream(urlConn.getOutputStream());
String str = jsonParam.toString();
byte[] data = str.getBytes("UTF-8");
printout.write(data);
printout.flush();
printout.close ();
And the MVC Controller as follow:
<System.Web.Http.AcceptVerbs("Post")> _
Public Function Android_Index(ByVal data As String) As ActionResult
Dim param As Dictionary(Of String, String) = JsonConvert.DeserializeObject(Of Dictionary(Of String, String))(data)
For Each p In param
LogEntry(p.Key & vbCrLf & p.Value, 0, "test")
Next
Return RedirectToLocal("/UI/Forbidden")
End Function
But I receive the data as empty-no element object. Please help to find where I am going wrong and how can I fix it?
UPDATE
I have tried to create a MVC class as follow:
Public Class SNC
Public snc As String
Public code As String
End Class
And edit the controller as follow:
Public Function Android_Index(ByVal data As SNC) As ActionResult
LogEntry(data.snc, 0, "test")
LogEntry(data.code, 0, "test")
......
End Function
When the android app tried to send the jsonobject, I can confirm the Android_Index has been hit. So I assume the jsonobject should accepted in the "data" parameter. But both "snc" and "code" are blank string. While I have re-check from the android that both "snc" and "code" which sent as jsonobject is not empty. For now, it seems the problem is in android side. Or the way how mvc should accept is not in correct way?
After hours with nothing, finally I can make it work.
The issue is on java side:
First I have to assign the jsonobject to a key as follow:
JSONObject jsonParam = new JSONObject();
jsonParam.put("snc", serialClient);
jsonParam.put("code", hashString(pwd + serialClient));
String param = "data=" + jsonParam.toString(); //assign jsonParam to identifier
Then set the Content-Type to application/x-www-form-urlencoded.
The post data finally catched correctly by the Controller.

Parsing JSON webservice result android

This is part of an AsyncTask that calls a web service that returns a JSON result. As you can see I hard coded the actual JSON return object. This was pulled directly from the error I got that specified it could not create the JSON object from the string object I was passing in, which is the variable result. That error occured when it hit new JSONObject(result) in the ParseResults method. Why would hard coding the exact string work but not the string being passed in?
#Override
protected void onPostExecute(String result) {
try {
result = "{\"Response\":{\"ReturnCode\":200,\"ReturnMessage\":\"Information Successfully Retrieved\",\"ReturnData\":null,\"ReturnClass\":{\"PRO_ID\":\"11111111-1111-1111-1111-111111111111\",\"PRO_FirstName\":\"SILVER\",\"PRO_LastName\":\"HIYO\"},\"FriendlyErrorMessage\":null}}";
JSONObject jsonObject = new ApiMethods().ParseResult(result);
ParseResults method snippet.
public JSONObject ParseResult(String result) throws JSONException
{
JSONObject returnedObject = new JSONObject();
try
{
JSONObject jsonObject = new JSONObject(result);
Also below, as i stated in a comment to another user, is the return statement that is returning the data. This is being returned from a .NET MVC application. I added in the UTF8 when that was mentioned and still get the same error.
return Json(data: new { Response = returnValue }, contentType: "application/json", contentEncoding: System.Text.Encoding.UTF8, behavior: JsonRequestBehavior.AllowGet);
And the entire error message:
org.json.JSONException: Value {"Response":{"ReturnCode":200,"ReturnMessage":"Information Successfully Retrieved","ReturnData":null,"ReturnClass":{"PRO_ID":"11111111-1111-1111-1111-111111111111","PRO_FirstName":"Silver","PRO_LastName":"HIYO"},"FriendlyErrorMessage":null}} of type java.lang.String cannot be converted to JSONObject
Seems like your hardcoded json object is not a valid json object. This may be the reason why it throws exception. Check validitiy of json object here first.
type java.lang.String cannot be converted to JSONObject
This means "Use getString() for String"
getJSONObject() may cause this error.
class Response {
String returnMessage;
...
}
Response response;
response.returnMessage= "msg";
JSONObjct obj;
obj = response.getJSONObject("ReturnMessage"); // cannot be converted
It maybe a encoding problem. Browser (and source editor) may have converted the result string encoding.
Q: ... I am storing items for the JSON data as Strings which is resulting in some odd character appearing
A: new String(jo.getString("name").getBytes("ISO-8859-1"), "UTF-8");
Android JSON CharSet UTF-8 problems
Hard coded JSON string is valid. If you want to try, replace (\") with (") and paste it to the checker.
{
"Response": {
"ReturnCode": 200,
"ReturnMessage": "Information Successfully Retrieved",
"ReturnData": null,
"ReturnClass": {
"PRO_ID": "11111111-1111-1111-1111-111111111111",
"PRO_FirstName": "SILVER",
"PRO_LastName": "HIYO"
},
"FriendlyErrorMessage": null
}
}
JSON object is like a structure (or class)
It looks like this.
class Response {
int ReturnCode = 200;
String ReturnMessage = "Information Successfully Retrieved";
...
}
Sample code.
protected void onPostExecute(String result)
{
JSONObject jsonObject;
JSONObject response;
int returnCode;
String returnMessage;
//JSONObject returnMessage;
result = "{\"Response\":{\"ReturnCode\":200,\"ReturnMessage\":\"Information Successfully Retrieved\",\"ReturnData\":null,\"ReturnClass\":{\"PRO_ID\":\"11111111-1111-1111-1111-111111111111\",\"PRO_FirstName\":\"SILVER\",\"PRO_LastName\":\"HIYO\"},\"FriendlyErrorMessage\":null}}";
try
{
jsonObject = new JSONObject(result);
response = jsonObject.getJSONObject("Response");
returnCode = response.getInt("ReturnCode");
returnMessage = response.getString("ReturnMessage");
//returnMessage = response.getJSONObject("ReturnMessage"); // This may cause same error
}
catch (JSONException e)
{
e.printStackTrace();
}
}
Use this site to validate your json string
http://jsonlint.com/

Categories

Resources