使用Gson时出现奇怪的“nameValuePairs”键

2022-09-01 21:59:55

我正在尝试从其字段重建一个(我将字段作为JSONObject获取),如下所示:Object

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

我使用这些行从Obeject

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

问题是当我用Gson解析main(jObj)时,我发现了一个名为的额外键。那么为什么我会得到这个钥匙呢?Object"nameValuePairs"

注意

  • 如果我这样做:在日志上,这个键消失了。jObj.toString();
  • 如果我这样做:我有Null作为结果(就像没有名为“nameValuePairs”的键一样)。jObj.opt("nameValuePairs");

这是我的实际结果:

enter image description here

这就是我期望拥有的:

enter image description here

我发现了与我的问题类似的问题,但它没有帮助。

是否有人有解决方案/解决方法,或者可以向我解释此密钥的来源?

谢谢。


答案 1

尝试使用Gson的而不是这样:JsonObjectJSONObject

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

答案 2

GSON 是 POJO 序列化的工具。如果您自己构建 JSONObject,则无需调用即可获取结果。gSon.toJSon(jObj);jObj.toString()

正确的GSON用法是为数据结构创建POJO对象。

您的根对象将如下所示:

public class jObj {
    JObj11 jObj11;
    JObj12 jObj12;
}

以这种方式定义整个结构后,您可以使用将其序列化为JSON,而无需使用JSONObject。GSON 将遍历它并生成 JSON 字符串。gSon.toJSon(jObj);

在您的示例中,GSON 尝试序列化 JSONObject Java 对象的内部结构,而不是它所表示的 JSON 结构。如您所见,JSONObject 使用 nameValuePair 来存储其内容。