我的问题很简单。我有一个java对象
public class Cat {
String id;
String name;
JSONObject ability;
// getter and setter
}
和一段代码
Cat cat = new Cat();
JSONObject ability = new JSONObject();
ability.put("catch", "mouse");
cat.setId("one");
cat.setName("Tom");
cat.setAbility(ability);
System.out.println(new JSONObject(new Gson().toJson(cat)));
这里是输出:
<块引用>{"name":"Tom","id":"one","ability":{"map":{"catch":"mouse"}}}
谁能告诉我为什么会出现“地图”?
答案 0 :(得分:3)
使用 com.google.gson.JsonObject 代替 org.json.JSONObject
答案 1 :(得分:2)
JSONObject
来自 org.json:json
图书馆,Gson
来自 com.google.code.gson:gson
。
您应该选择一个库并使用它。这些库不知道如何处理彼此之间的类。
回答您的实际问题:Gson
将 JSONObject
视为任何其他类,只需对其字段进行序列化即可。
JSONObject
有一个字段
private final Map<String, Object> map;