Reputation: 6470
I have this code
String resultStr = result.getString("result");
String testStr = "{\"movielens\":{\"searchMovie\":{\"code\":400,\"data\":\"Access Denied\"}}}";
Log.e("result", resultStr);
Log.e("teststr", testStr);
JSONObject testJson = new JSONObject(testStr);
JSONObject resultJson = new JSONObject(resultStr);
which normally parsing json from the web. The testStr here is the string that i copy in the logcat by hand and try to put it to test if it is error or not.
and this is the result :
02-13 12:16:44.570: E/json result(23439): {"statusCode":200,"result":"{\"movielens\":{\"searchMovie\":{\"code\":400,\"data\":\"Access Denied\"}}}","success":true}
02-13 12:16:44.575: E/result(23439): {"movielens":{"searchMovie":{"code":400,"data":"Access Denied"}}}
02-13 12:16:44.575: E/teststr(23439): {"movielens":{"searchMovie":{"code":400,"data":"Access Denied"}}}
02-13 12:16:44.575: W/System.err(23439): org.json.JSONException: Value of type java.lang.String cannot be converted to JSONObject
02-13 12:16:44.580: W/System.err(23439): at org.json.JSON.typeMismatch(JSON.java:107)
02-13 12:16:44.580: W/System.err(23439): at org.json.JSONObject.<init>(JSONObject.java:158)
02-13 12:16:44.585: W/System.err(23439): at org.json.JSONObject.<init>(JSONObject.java:171)
02-13 12:16:44.585: W/System.err(23439): at com.abac.recommender.movielensdemo.BaseActivity$MakeRequest.onPostExecute(BaseActivity.java:176)
02-13 12:16:44.585: W/System.err(23439): at com.abac.recommender.movielensdemo.BaseActivity$MakeRequest.onPostExecute(BaseActivity.java:1)
It always error at this line JSONObject resultJson = new JSONObject(resultStr);
which is the json i get from the web but why testStr is not error when convert it to json? Both string look identical?
So i test equality for them like this
Log.e("compare", "" + resultStr.equals(testStr));
and i get
02-13 12:25:20.940: E/compare(23912): false
So, what are the difference and how can i get this to work?
Thanks.
Upvotes: 0
Views: 302
Reputation: 18923
Some times what happen when you are fetching data from the server at that time some un-wanted characters was added when you compose the String. So try this it will help you.
Instead of return only json object change from
return urJsonObject;
to
return new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1)
Upvotes: 3