我想使用 Eclipse 学习 Java 中的 JSON 数据存储,所以我用 google 搜索了很多。
我找到了JSON.simple和 GSON 。这些是一个好的选择吗?
我转到属性>> Java 构建路径>> 添加外部 JAR
。我添加了json-simple-1.1.1.jar和 google-gson-2.2.4-release.zip 。这样对吗? JavaDoc 位于哪里?
主要问题涉及此处找到的示例:JSON.simple example – Read and write JSON ,其中介绍了 JSON.simple。 我编写了以下代码:
JSONObject object = new JSONObject();
JSONArray array = new JSONArray();
array.add("Bob");
array.add("John");
object.put("nicknames", array);
object.put("from", "US");
object.put("age", 35);
try {
String path = "";
FileWriter file = new FileWriter(path);
String json = object.toJSONString();
file.write(json);
file.close();
} catch (IOException io) {
// Fail
}
但我收到以下警告。这些是什么意思?
Type safety: The method add(Object) belongs to the raw type ArrayList. References to generic type ArrayList should be parameterized on 'JSONArray.add'
Type safety: The method put(Object, Object) belongs to the raw type HashMap. References to generic type HashMap<K,V> should be parameterized on 'JSONObject.put'
顺便说一句,我如何美化我的 JSON?
最佳答案
I found JSON.simple and GSON. Are those a good choice?
目前我非常喜欢前者,但后者功能更多,使用更广泛,并且始终是最新的。
Where is the JavaDoc located?
对于 JSON.simple,请参阅 this answer在网站上。 对于GSON,请关注this link .
I get some warnings. What do they mean?
这些类的声明没有其父类(super class)的类型参数:
public class JSONObject extends HashMap {
// ...
}
public class JSONArray extends ArrayList {
// ...
}
当您调用 put()
或 add()
时,它们是在父类(super class)中定义的,而该父类(super class)未正确参数化。
您可以做的是将@SuppressWarnings("unchecked")
添加到容器中。
How can I prettify my JSON?
JSON.simple 无法做到这一点,但 GSON 可以:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
关于java - 在Java中存储JSON数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23956154/