Json response should look like :
"{\"syncrequest\":{\"user\":{\"#xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\",\"active\":\"true\",\"basedataset\":\"false\"},\"syncversion\":\"89\",\"syncdata\":[{\"operation\":\"INSERT
OR
REPLACE\",\"table\":\"WSInformation\",\"rows\":[{\"WS_ID\":\"71\",\"WS_ParentOwn\":null,\"WS_Notes\":\"Notes\\"for\\"VistaStore
Fleet\\"save\",\"CC_ID\":\"1\",\"Record_Instance\":\"1\",\"Record_LastModified\":\"2013-11-26T07:51:35.203\"}]}]}}"
Response coming from server with a string format. When i convert the above string in json format using
JsonObject jObject =new JsonObject(string);
its getting error like unterminated character in string.
Can any body help me out for above problem.
Thanks In advance
Edited :
The response coming from server is in the form of input stream .
So, I used to convert the inputstream to string using the function :
IOUtils.readStream(instream);
Then the response string should like :
string response =
"{\"syncrequest\":{\"user\":{\"#xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\",\"active\":\"true\",\"basedataset\":\"false\"},\"syncversion\":\"89\",\"syncdata\":[{\"operation\":\"INSERT
OR
REPLACE\",\"table\":\"WSInformation\",\"rows\":[{\"WS_ID\":\"71\",\"WS_ParentOwn\":null,\"WS_Notes\":\"Notes\\"for\\"VistaStore
Fleet\\"save\",\"CC_ID\":\"1\",\"Record_Instance\":\"1\",\"Record_LastModified\":\"2013-11-26T07:51:35.203\"}]}]}}"
By using the below function to form the json object,I removing the double quotes.
res = response.substring(1, response.length() - 1);
and removing double quotes with in the string using the below function.
res = response.replace("\\"", "\"");
Don't use JsonObject in conversion.
JSONObject jObject = new JSONObject(response);
JSONArray jArray = jObject.getJSONArray("syncrequest");
import this org.json.JSONObject;
not com.google.gson.JsonObject;
I think it's not a valid JSON-object.
Related
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.
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\"
I'm wondering what is the difference between using a JSONObject and JSONTokener to parse a JSON string.
I have seen examples where either of these classes were used to parse a JSON string.
For example, I parsed a JSON string like this:
JSONObject object = (JSONObject) new JSONTokener(jsonString).nextValue();
return object.getJSONObject("data").getJSONArray("translations").
getJSONObject(0).getString("translatedText");
But I also see examples where they simply use a JSONObject class (without using JSONTokener) to parse it:
String in;
JSONObject reader = new JSONObject(in);
JSONObject sys = reader.getJSONObject("sys");
country = sys.getString("country");
I read the description on this page, but still don't really get the difference. Is one better than the other performance wise and when should a JSONTokener be used?
Thanks!
Im using JsonObject to parse a response from an API, the problem is that the resulting String have double quotes, how to get string with no quotes?
JsonElement jelement = new JsonParser().parse(response);
JsonObject jobject = jelement.getAsJsonObject();
String authorization = jobject.get("authorization").toString();
Log.d("mensa","parseado jwt :"+authorization);
so my response looks like...
parseado jwt :"eyJ0eXAiOiJKV1QiLCJhbGciO..."
Actual Json response
{
"authorization": "eyJ0eXAiOiJKV1..."
}
what is the right way to parse this string so i dont get it wrapped with double quotes?
I believe you are using GSON library. No need to trim out your result, gson provide methods for that. try this
String authorization = jobject.get("authorization").getAsString();
Refer Gson API Doc : JsonElement
You are getting Object from Json and then converting to String. jobject.get("authorization").toString(); try to get String.
String authorization = jobject.getString("authorization");
Just trim out the quotes: authorization = authorization.substring(1, authorization.length() - 1)
Edit: You should actually use the getString() method as it will return the actual content as a string, however, the above still works as a quick workaround.
I am trying to parse JSON from web service. But i get "String could not be converted to Json Object" error.
My json: {"encoding":"UTF-8","yorumlar":[["dogukan","deneme yorumu"],["Burak","yorum"]]}
I get this string like below;
HttpClient client = new DefaultHttpClient();
HttpUriRequest request = new HttpGet(url);
HttpResponse response = null;
try
{
response = client.execute(request);
String jsonString = StreamUtils.convertToString(response.getEntity().getContent());
JSONObject json = new JSONObject(jsonString);
.
.
.
When i got this string from web service like above, i get this error but when i do that:
JsonObject object = new JsonObject("{\"encoding\":\"UTF-8\",\"yorumlar\":[[\"dogukan\",\"deneme yorumu\"],[\"Burak\",\"yorum\"]]}")
i don't get this error. So, the strings are the same and json format is ok. What is the problem?
I solved the problem, the json string starts with these characters "". But these characters does not appear in debug mode. I created a java project. And i got the json string from server. I saw these characters in debug mode. Java project gave me more details about the converting error.
if you try to get the values of these in debug mode:
jsonString.toCharArray()[0] and jsonString.toCharArray()[1]
you will see the values as "", not "{". It's not space but does not appear. and "{" character located in 2. index.
We have solved the problem on server side. I guess that was an page encoding problem.