Strange “nameValuePairs” key appear when using Gson

前端 未结 5 1361
我寻月下人不归
我寻月下人不归 2021-02-12 10:17

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         


        
5条回答
  •  渐次进展
    2021-02-12 11:18

    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;
    }
    

提交回复
热议问题