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.