【发布时间】:2018-04-27 09:53:02
【问题描述】:
在我的代码中,我需要将org.json.JSONObject 添加到另一个使用gson.toJson 序列化的对象。但是,当这个对象被序列化时,JSONObject 中的值会被 gson 本身嵌套到一个映射键中。例如,
public class New {
private static final Gson gson = new GsonBuilder().disableHtmlEscaping().create();
public static void something(User user) throws Exception {
try {
ObjectWriter ow = new ObjectMapper().writer();
String json = ow.writeValueAsString(user);
JSONObject maskedUser = new JSONObject(json);
Nesting testing = new Nesting(maskedUser, "someting");
String something = gson.toJson(testing);
System.out.println(something);
} catch (Exception e) {
throw e;
}
}
public static void main(String[] args) throws Exception {
User user = new User("a", "b", "c");
something(user);
}
}
我收到这样的输出 JSON
{"details":{"map":{"lastname":"b","firstname":"a","password":"c"}},"sometim":"someting"}
我需要知道如何避免 gson 解析器自动添加的 map 键。
编辑:我刚刚发现 gson 在序列化对象内的数组时还添加了"myArrayList"。这非常令人沮丧,并且使解析 JSON 变得困难和烦人。
"map":{"fruits":{"myArrayList":["Apples"]}
【问题讨论】: