Strange “nameValuePairs” key appear when using Gson

前端 未结 5 1360
我寻月下人不归
我寻月下人不归 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:08

    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 toMap(JSONObject content) {
            final Map map = new HashMap<>(content.length());
            for (final Iterator iterator = content.keys(); iterator.hasNext(); )          {
                final String key = iterator.next();
                map.put(key, get(key));
            }
            return map;
        }
    
    
      public static  String objectToJson(T object) {
         Gson gson = new GsonBuilder().setPrettyPrinting().create();
         return gson.toJson(object);
      }
    

提交回复
热议问题