I have run into an issue where I try to parse a serialised json string to a JSONObject to later retrieve key values for another object, PetFedInfo. I make the called from my android app to an ASP.NET web API and the string returns successfully.
Here is the code where I parse the result from the asp.net api server:
JSONObject jsonObj = new JSONObject();
try {
String stringFromServer = PostHTTP(Constants.POST_PET_GETFEDINFO,jObj);
Log.v("stringFromServer",stringFromServer);
Log.v("directCallResult",PostHTTP(Constants.POST_PET_GETFEDINFO,jObj));
Log.v("actualString","{\"petName\":\"nn\",\"lastFedTime\":\"\"}");
jsonObj = new JSONObject("{\"petName\":\"nn\",\"lastFedTime\":\"\"}");
Log.v("jsonObjFromManualString",jsonObj.toString());
jsonObj = new JSONObject(PostHTTP(Constants.POST_PET_GETFEDINFO,jObj));
Log.v("jsonObjFromDirectCall",jsonObj.toString());
} catch (JSONException e) {
e.printStackTrace();
}
After I run the app in debug mode, the string from the instance 'stringFromServer' (Logged as 'stringFromServer') throws an error when I attempt to create a JSONObject:
org.json.JSONException: Value {"petName":"mm","lastFedTime":""} of type java.lang.String cannot be converted to JSONObject
at org.json.JSON.typeMismatch(JSON.java:112)
W/System.err: at org.json.JSONObject.<init>(JSONObject.java:168)
at org.json.JSONObject.<init>(JSONObject.java:181)
at com.FeedMyPet.helper.WebRequestManager$2.run(WebRequestManager.java:102)
Whereas the string where I manually enter (logged as 'actualString') successfully creates the JSON object. I have printed out all string values to the console using Log.v and they almost have the same output
V/stringFromServer: "{\"petName\":\"v\",\"lastFedTime\":\"\"}"
V/directCallResult: "{\"petName\":\"v\",\"lastFedTime\":\"\"}"
V/actualString: {"petName":"nn","lastFedTime":""}
I have reviewed the construction for JSONObject and it accepts a String:
public JSONObject(String json) throws JSONException {
this(new JSONTokener(json));
}
I'm a little lost as to why the serialised object using quotation marks (no object?) successfully creates the object, and a String instance cannot. How can I get the String object to match the result of 'actualString'?
Can someone please point me in the right direction?