java - 在Java中存储JSON数据

标签 java json gson json-simple

我想使用 Eclipse 学习 Java 中的 JSON 数据存储,所以我用 google 搜索了很多。

我找到了JSON.simpleGSON 。这些是一个好的选择吗?

我转到属性>> Java 构建路径>> 添加外部 JAR。我添加了json-simple-1.1.1.jargoogle-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/

相关文章:

java - 在运行时修改Android应用程序

java - 正则表达式查找代码注释中的坏词

javascript - JSON jQuery 问题

android - 将 GSON 与烂番茄 API 结合使用时出现的问题(Android)

java - 如果类声明无法更改,如何在序列化时或多或少地全局更改生成的 Json?

Mac OS X Lion 上的 Java 1.6.0_26

java - 在 Java 中,当文件被其他线程锁定时,有没有办法读取该文件?

javascript - Javascript 中形成的 URL 无效

json - 字段 'browser' 不包含 react 的有效别名配置

java - gson.JsonObject 和类加载造成非常奇怪的情况