Seen this thread for possible solutions but it beats me.
I store a customer data object as a JSON String in shared preferences (Android) and try to retrieve the string convert back to customer object and use for validations. The conversion from object to JSON String occurs perfectly well and stores in preferences (as a key value(string) pair).
When I try to create a JSONObject or an array (Its not an array but tried anyway) using the SharedPreferences.getString(key,"") - I always get the same error "Value ... of type java.lang.String cannot be converted to JSONObject".
I am hoping a different pair of eyes catch something I could not.
Error message with data (masked):
Value
{"address":{"city":"city","country":"country","customer_address_id":0,"customer_id":0,"house_number":"#123, Lane 1, Street 1","latitude":0.0,"longitude":0.0,"postcode":"12001","street":"Lane 2, Street 2"},"ageGroup":"25-45","dateOfBirth":"1537308474000","email":"abc#abc.com","firstName":"abcdefg","gender":"","id":"108","lastName":"xyz","locale":"en_us","middleName":"none","phone":"1234567890","uuid":"8c3ce2c5-600f-3c4e-bc07-727d61fae7ff"}
of type java.lang.String cannot be converted to JSONObject.
All am trying to do is (gist of code):
Saving to shared prefs using below:
jsonAdapter = moshi.adapter(RegisterUser.class);
mRegisterUser = (RegisterUser) jsonAdapter.fromJson(regisCustUser.toString());
prefs = UserPrefs.getUserPrefs(getApplicationContext());
prefs.setPrefsItem(UserPrefs.getregUserKey(), jsonAdapter.toJson(mRegisterUser));`
where setPrefsItem does below:
JsonAdapter jsonAdapter = moshi.adapter(javaObject.getClass());
String cartJson = jsonAdapter.toJson(javaObject);
// Log.e("CartJsonreflection", cartJson);
editor.putString(prefKey, cartJson);
editor.commit();
Here is where retrieve occurs:
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
...
private static SharedPreferences settings;
...
public static Object someMethod(String prefKey, Object javaObject) {
String prefJson = settings.getString(prefKey, "");
JSONObject regisCustomer = new JSONObject(prefJson);
javaObject = (someObject) jsonAdapter.fromJson(regisCustomer.toString());
// casting is redundant but added for clarity
return javaObject;
}
Where prefJson has the above string.
I have tried to validate the JSON string on two websites - https://jsoneditoronline.org/ and https://jsonlint.com/
I have even pasted the string in Notepad++ for any special characters but found none.
Might be the case that you are trying to convert the empty string which the default string to JSONObject .
Make sure you are getting a value in prefJson by , making sure that you have initialized the SharedPreferenceswith the correct key and the key for the getString() is also right.
var s ="{\"address\":{\"city\":\"city\",\"country\":\"country\",\"customer_address_id\":0,\"customer_id\":0,\"house_number\":\"#123, Lane 1, Street 1\",\"latitude\":0.0,\"longitude\":0.0,\"postcode\":\"12001\",\"street\":\"Lane 2, Street 2\"},\"ageGroup\":\"25-45\",\"dateOfBirth\":\"1537308474000\",\"email\":\"abc#abc.com\",\"firstName\":\"abcdefg\",\"gender\":\"\",\"id\":\"108\",\"lastName\":\"xyz\",\"locale\":\"en_us\",\"middleName\":\"none\",\"phone\":\"1234567890\",\"uuid\":\"8c3ce2c5-600f-3c4e-bc07-727d61fae7ff\"}";
val regisCustomer = JSONObject(s)
println(regisCustomer.toString())
Since hardcoding the string with your value worked .
Try below
Gson gson = new GsonBuilder().create();
public static <T> T someMethod(String prefKey, Class<T> type) {
String prefJson = settings.getString(prefKey, "");
return gson.fromJson(prefJson , type);
}
Solution includes pieces of answers from other post.
I had to do:
prefJson= prefJson.replace("\\\"", "\"");
prefJson = prefJson.substring(prefJson.indexOf("{"), prefJson.lastIndexOf("}") + 1);
The quirky thing was the sharedpreferences had the exact string as below (including start and end quotes('"') in the value. Not sure why that was an issue, only when passed as a parameter. The quotes and the escape characters were ignored when hard coded into the string variable:
"{\"address\":{\"city\":\"City\",\"country\":\"Country\",\"customer_address_id\":0,\"customer_id\":0,\"house_number\":\"#123, Lane 1, Street 1\",\"latitude\":0.0,\"longitude\":0.0,\"postcode\":\"PA 12345\",\"street\":\"Lane 2, Street 2\"},\"ageGroup\":\"25-45\",\"dateOfBirth\":\"1537368909000\",\"email\":\"abc#abc.com\",\"firstName\":\"First Name\",\"gender\":\"\",\"id\":\"119\",\"lastName\":\"Last Name\",\"locale\":\"en_us\",\"middleName\":\"none\",\"phone\":\"0987654321\",\"uuid\":\"8c3ce2c5-600f-3c4e-bc07-727d61fae7ff\"}"
which had to be converted to:
{"address":{"city":"City","country":"Country","customer_address_id":0,"customer_id":0,"house_number":"#123, Lane 1, Street 1","latitude":0.0,"longitude":0.0,"postcode":"PA 12345","street":"Lane 2, Street 2"},"ageGroup":"25-45","dateOfBirth":"1537368909000","email":"abc#abc.com","firstName":"First Name","gender":"","id":"119","lastName":"Last Name","locale":"en_us","middleName":"none","phone":"0987654321","uuid":"8c3ce2c5-600f-3c4e-bc07-727d61fae7ff"}
Note: Moderators, please feel free to remove or merge this questiont if this sounds repetitive.Thank you everyone.
{
"id": "1",
"name": "test1",
"data_city": "a:35: {i:22;s:6:\"61,800\";i:23;s:6:\"61,800\";i:24;s:6:\"61,800\";i:25;s:6:\"61,800\" ;i:26;s:6:\"61,800\";i:27;s:6:\"61,800\";i:28;s:6:\"61,800\";i:29;s:6:\"61,800\";i:30;s:6:\"61,800\";i:31;s:6:\"61,800\";i:54;s:6:\"61,800\";i:16;s:6:\"61,800\";i:32;s:6:\"61,800\";i:52;s:6:\"61,800\";i:21;s:6:\"61,800\";i:33;s:6:\"61,800\";i:37;s:6:\"61,800\";i:34;s:6:\"61,800\";i:36;s:6:\"61,800\";i:38;s:6:\"61,800\";i:41;s:6:\"61,800\";i:35;s:6:\"61,800\";i:39;s:6:\"61,800\";i:40;s:6:\"61,800\";i:42;s:6:\"61,800\";i:44;s:6:\"61,800\";i:43;s:6:\"61,800\";i:46;s:6:\"61,800\";i:45;s:6:\"61,800\";i:47;s:6:\"61,800\";i:49;s:6:\"61,800\";i:53;s:6:\"61,800\";i:50;s:6:\"61,800\";i:48;s:6:\"61,800\";i:51;s:6:\"61,800\";}"
}
This is my json response
i need to get data from string data_city
First of all, your JSON is not valid - probably a copy paste error.
Anyway, there are several ways to do this. One option is to use the built in JSONObject type:
String jsonString = "YOUR_JSON_STRING";
JSONObject objJSON = new JSONObject(jsonString);
String dataCity = objJSON.getString("data_city");
Hope this helps. Be sure to run your JSON String through a validation tool first. This one works nicely: https://jsonformatter.curiousconcept.com/
I have some UNICODE characters in my response like this:
"city": "Bel\\u00e9m"
and it is parsed like this:
city = "Bel\u00e9m"
But i expect it to be:
city = "Belém"
What is going wrong here and what should i do to have a properly parsed unicode character in my response?
String auto convert unicode characters to letters.
So save your response to a string variable and then make JSON from that string object.
String myString = "city": your json response;
then make json object from myString
JSonObject obj = new JSonObject(myString);
may it help you.
try this out,
Html.fromHtml(city.replaceAll("\\","\"));
suppose I have {"data": {"243232": {"id": "testid","name": "test" } }}
so how to get correct value thanks.
you cant directly pass above String with Gson as "243232" is number and we cant declare variable which start from number, So for parsing this you must modify the string with some notification
i.e. {"data": {"temp243232": {"id": "testid","name": "test" } }}
here i modified string manually "243232" by "temp243232", now you can parse it
You can use a JSON parser for Java like Google GSON. This works best if the class whose object your data in json represents, is known to you.
String str = ""; //contains your json string
Gson gson = new Gson();
MyClass var = gson.fromJson(str,MyClass.class);
where MyClass will be a class which represents the object.
Then you can access data just like you'd do from a data structure in your program, it'll be something like var.data.
I want to convert from JSONObject
{"CNo":80,"CName":"ganesh","CMail":"ganesh#ganesh.com","CMailType":"home","CPhNo":9878987776,"CPhNoType":"home","ClientNo":1}
to
{\"CNo\":80,\"CName\":\"ganesh\",\"CMail\":\"ganesh#ganesh.com\",\"CMailType\":\"home\",\"CPhNo\":9878987776,\"CPhNoType\":\"home\",\"ClientNo\":1}
Try to use toString() on your JSON object
I hope this helps. Just learnt it yesterday :)
JSONObject foo = yourJSONOject;
String uid = foo.get("CNo").isString().toString();
String type = foo.get("CName").isString().toString();
.
. //for each Key field.
I am not sure why you have put the escapes in the string, but you can call append() and get the OP as you want it.
Below code will convert the given JsonObject to string.
Gson gson = new Gson();
String bodyInStringFormat = gson.toJson(passYourJsonObjectHere);