I am trying to rebuild an Object
from its fields( i get the fields as a JSONObject), something like this:
JSONObject jObj = new JSONObject();
JSO
Finally, I found a solution for this problem. Instead of saving my JSONObject using Gson, I will simply save it as string using toString() and rebuild the original JSONObject later by wrapping saved string into JSONArray as in following example.
In my case i din't have choice to change JSONObject to com.google.gson.JsonObject as suggested in accepted answer because my 90% coding was done and such a change would have ruined my days and nights. Following is the piece of code that worked for me:
For example, save JSONObject to shared preference (or DB) like this:
public void saveJson(JSONObject reqJson) {
sharedPref.editor().put("savedjson_key",reqJson.toString()).apply();
}
Then, when you want to rebuild the original JSONObject:
public JSONObject getSavedJson() {
String reqJson=sharedPref.getString("savedjson_key");
if (reqJson != null) {
try {
JSONArray arr = new JSONArray(("["+reqJson+"]").replaceAll("\\\\", ""));
return arr.getJSONObject(0);
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}