使用gson问题将jsonobject转换为字符串

nic*_*ica 5 java json gson

我尝试使用 GSON 库将 JsonObject 转换为字符串。但结果输出将有一层父“map”包裹 json。请告诉我我做错了什么,为什么父“地图”图层会出现?

我什至尝试使用 new Gson().toJson(bean); 来隐藏 bean 但输出结果还有一层父“map”包裹着json。

我需要通过使用满足的条件

1) Mutable object
2) GSON
3) method might handle other object Type
Run Code Online (Sandbox Code Playgroud)

Maven 项目使用如下库:

<dependency>
  <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.5</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

Java代码如下(仅理解非真实代码的示例,将在T中使用):

List<JSONObject> records = new ArrayList <JSONObject> ();           
JSONObject bean = new JSONObject();

bean.put("A", "is A");    
bean.put("B", "is B lah");    
bean.put("C", "is C lah");    
bean.put("D", "is D");    

records.add(bean);

String JSONBody2 = new Gson().toJson(records);
Run Code Online (Sandbox Code Playgroud)

我期望输出是 [{"D":"is D","A":"is A","B":"is B lah","C":"is C lah"}]

但实际输出是 [{"map":{"D":"is D","A":"is A","B":"is B lah","C":"is C lah"}}]

实际代码如下

public String Json( String json, List<T>  list) {
   String JSONBody = new Gson().toJson(list);
}
Run Code Online (Sandbox Code Playgroud)

我需要使用 gson 进行序列化,这就是我放置 T 的原因。但我不知道为什么“地图”出现在这里。和以前一样,它无需父“地图”包装即可工作。(相同的代码和相同的库只是新重新创建的项目但有这个问题)

Ami*_*Rai 1

使用JSONArray而不是 List ,它将为您提供所需的输出:

JSONArray  records = new JSONArray();           
JSONObject bean = new JSONObject();

bean.put("A", "is A");
bean.put("B", "is B lah");    
bean.put("C", "is C lah");    
bean.put("D", "is D");    

records.put(bean);

String JSONBody2 = new Gson().toJson(records);
Run Code Online (Sandbox Code Playgroud)