我是 JSON Universe 的新手,希望在 JSON 文件中以有意义的方式存储多个 JSONObject。 JSONObjects 以 JSON 语法格式化的字符串形式提供给函数,具有多个属性:
- 唯一标识符,此处为 java.util.UUID(通用唯一标识符)
- 姓名
- 年龄
- 评论(随机字符串)
例如:
{"name":"Peter","ID":"bc6fe168-e73f-48c9-b421-ad3c4c424392", "Age":"23","Comment":"I am a new User"}
我的想法是,加载 json 文件并将条目存储在列表中。然后我检查 UUID 是否已经存在。如果不是,我将在列表末尾创建一个新条目,如果它已经在那里,我将更新该条目的其他属性。
这是我到目前为止所拥有的:
public void updateFile(String user) {
/* String to JSONObject */
JSONObject newUser = new JSONObject(content);
/* Load JSON File */
String content = readFile("C:\\localProjects\\list.json");
/* Add or update "newUser" */
if(boolean isNew = containsID(getID(newUser),content))
content.append(user);
else
updateUser(newUser);
}
此方法适用于我的用例,但对我来说它看起来不是很有效,并且不是真正的 OOP 方法。它也不是很鲁棒,例如,如果我添加一个新用户,其名称在另一个条目中用作 UUID,它会编辑错误的用户,而不是将其添加为新用户。
是否有可以轻松帮助我的功能,例如: 将现有 JSON 作为 JSON 列表加载,迭代对象中的 JSON 对象,编辑特定变量?
最佳答案
使用类似 Jackson 的工具,你可以
- 创建一个合适的 POJO
User.java
,你甚至可以使用 JsonNode - 将每个用户读入您的 java 对象
- 使用标识符作为键将每个用户存储到
HashMap
中 - 将列表写入,例如
标准输出
示例
此示例将用户数组读取到 JsonNode
对象。 ID
字段可通过 JsonPointer 访问语法。
@Test
public void json3() throws JsonParseException, JsonMappingException, IOException {
Map<String, JsonNode> store = new HashMap<>();
ObjectMapper mapper = new ObjectMapper();
JsonNode users = mapper.readValue(
"[{\"name\":\"Peter\",\"ID\":\"bc6fe168-e73f-48c9-b421-ad3c4c424392\", \"Age\":\"23\",\"Comment\":\"I am a new User\"},{\"name\":\"jschnasse\",\"ID\":\"bc6fe168-e73f-48c9-b421-ad3c4c424393\", \"Age\":\"well\",\"Comment\":\"I am a fun User\"}]",
JsonNode.class);
users.forEach((user) -> {
String id = user.at("/ID").asText();
if (!store.containsKey(id)) {
store.put(id, user);
} else {
/* Do something else */
}
});
System.out.println(toString(store.values()));
}
public String toString(Object obj) {
try (StringWriter w = new StringWriter();) {
new ObjectMapper().configure(SerializationFeature.INDENT_OUTPUT, true).writeValue(w, obj);
return w.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
打印
[ {
"name" : "jschnasse",
"ID" : "bc6fe168-e73f-48c9-b421-ad3c4c424393",
"Age" : "well",
"Comment" : "I am a fun User"
}, {
"name" : "Peter",
"ID" : "bc6fe168-e73f-48c9-b421-ad3c4c424392",
"Age" : "23",
"Comment" : "I am a new User"
} ]
关于java - 加载 JSON 文件,迭代条目并在 Java 中编辑它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52738960/