25

I am trying to rebuild an Object from its fields( i get the fields as a JSONObject), something like this:

JSONObject jObj = new JSONObject();  

JSONObject jObj1 = new JSONObject(); 
JSONObject jObj2 = new JSONObject(); 

JSONObject jObj21 = new JSONObject(); 
JSONObject jObj22 = new JSONObject(); 

jObj1.put("jObj11", "value11");
jObj1.put("jObj12", "value12");


jObj21.put("jObj211", "value211"); // level 2 
jObj21.put("jObj212", "value212");
jObj21.put("jObj213", "value213");

jObj22.put("jObj221", "value221");
jObj22.put("jObj222", "value222");
jObj22.put("jObj223", "value223");

jObj2.put("jObj21", jObj21);  // level 1 
jObj2.put("jObj22", jObj22);

jObj.put("jObj1", jObj1); // level 0 
jObj.put("jObj2", jObj2);

I use those lines to get Json from an Obeject

GsonBuilder builder = new GsonBuilder();
Gson gSon = builder.create();
gSon.toJSon(jObj);

The Problem is when i parse the main Object ( jObj ) with Gson, i found an extra key named "nameValuePairs". So why i get this key?

Notice:

  • If i do : jObj.toString(); on Log, this key disappear.
  • If i do : jObj.opt("nameValuePairs"); i have Null as result (like there is no key named "nameValuePairs").

This is my actual result:

enter image description here

And this is what i expect to have:

enter image description here

I found something similar to my problem, but it doesn't help.

Is there someone who have a solution/workaround or can explain me the origin of this key?

Thanks.

Community
  • 1
  • 1
Rami
  • 7,879
  • 12
  • 36
  • 66

5 Answers5

41

Try to use Gson's JsonObject instead of JSONObject like this:

 JsonObject jObj = new JsonObject();

    JsonObject jObj1 = new JsonObject();
    JsonObject jObj2 = new JsonObject();

    JsonObject jObj21 = new JsonObject();
    JsonObject jObj22 = new JsonObject();

    jObj1.addProperty("jObj11", "value11");
    jObj1.addProperty("jObj12", "value12");


    jObj21.addProperty("jObj211", "value211"); // level 2
    jObj21.addProperty("jObj212", "value212");
    jObj21.addProperty("jObj213", "value213");

    jObj22.addProperty("jObj221", "value221");
    jObj22.addProperty("jObj222", "value222");
    jObj22.addProperty("jObj223", "value223");

    jObj2.add("jObj21", jObj21);  // level 1
    jObj2.add("jObj22", jObj22);

    jObj.add("jObj1", jObj1); // level 0
    jObj.add("jObj2", jObj2);

    String json = new Gson().toJson(jObj);
nbaroz
  • 1,795
  • 13
  • 14
  • I have members instead nameValuePairs with Gson, Is it possible to have nothing? – Pablo R. Aug 14 '18 at 08:27
  • This works if you plan to build each JsonObject--meaning you have the key,value pairings--but what if you have JsonObject String? With JSONObject you can create JSONObject by passing in only the String. You can't do that with JsonObject. – portfoliobuilder Dec 30 '20 at 17:05
  • For me the best solution and for people that need to store objects as values check this [question](https://stackoverflow.com/questions/22585970/how-to-add-an-object-as-a-property-of-a-jsonobject-object) – Manuel Felipe Garcia Rincon May 18 '22 at 21:35
7

GSON is a tool for POJO serialization. If you are building JSONObject by yourself there is no need for gSon.toJSon(jObj); you can just call jObj.toString() to get the result.

The proper GSON usage would be to create POJO object for your data structure.

Your root object would look like this:

public class jObj {
    JObj11 jObj11;
    JObj12 jObj12;
}

After the whole structure is defined this way you can use gSon.toJSon(jObj); serialize it to JSON without any usage of JSONObject. GSON will traverse it and produce the JSON string.

In your example, GSON tries to serialize the internal structure of the JSONObject Java object, not the JSON structure it represents. As you can see, JSONObject uses nameValuePair to store it's content.

atok
  • 5,880
  • 3
  • 33
  • 62
6

I had the same problem when I wanted to use Gson only for pretty print. JsonObject is working fine but if you still want to use JSONObject instead of JsonObject then you can use it that way:

public class JsonUtil {
    public static String toPrettyFormat(String jsonString)
    {
        JsonParser parser = new JsonParser();
        JsonObject json = parser.parse(jsonString).getAsJsonObject();

        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String prettyJson = gson.toJson(json);

        return prettyJson;
    }
}

and simply pass JSONObject as string like this:

String prettyJson = JsonUtil.toPrettyFormat(jsonObject.toString());
0

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;
}
Vinay
  • 1,859
  • 22
  • 26
0

You can use this solution:

   //org.json.JSONObject 
   JSONObject jObj = new JSONObject();  

  //com.google.gson.JsonObject
  JsonObject jObj1 = new JsonObject();
  jObj1.addProperty("jObj11", "value11");

  JsonObject jObj2 = new JsonObject();
  jObj2.addProperty("jObj12", "value12");

  //JSONObject put(String name, Object value)
  jObj.put("jObj1", jObj1); 
  jObj.put("jObj2", jObj2);

  //Result
   objectToJson(toMap(jObj));

  public Map<String, Object> toMap(JSONObject content) {
        final Map<String, Object> map = new HashMap<>(content.length());
        for (final Iterator<String> iterator = content.keys(); iterator.hasNext(); )          {
            final String key = iterator.next();
            map.put(key, get(key));
        }
        return map;
    }


  public static <T> String objectToJson(T object) {
     Gson gson = new GsonBuilder().setPrettyPrinting().create();
     return gson.toJson(object);
  }
MrZ
  • 560
  • 2
  • 12