我正在编写一个功能,我在其中读取和写回json。但是,我可以从文件中读取json元素,但无法编辑相同的加载对象。这是我正在处理的代码。
InputStream inp = new FileInputStream(jsonFilePath);
JsonReader reader = Json.createReader(inp);
JsonArray employeesArr = reader.readArray();
for (int i = 0; i < 2; i++) {
JsonObject jObj = employeesArr.getJsonObject(i);
JsonObject teammanager = jObj.getJsonObject("manager");
Employee manager = new Employee();
manager.name = teammanager.getString("name");
manager.emailAddress = teammanager.getString("email");
System.out.println("uploading File " + listOfFiles[i].getName());
File file = insertFile(...);
JsonObject tmpJsonValue = Json.createObjectBuilder().add("fileId", file.getId()).add("alternativeLink",file.getAlternateLink()).build();
jObj.put("alternativeLink", tmpJsonValue.get("alternativeLink")); <-- fails here
}
运行时出现以下异常。
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractMap.put(AbstractMap.java:203)
at com.mongodb.okr.DriveQuickstart.uploadAllFiles(DriveQuickstart.java:196)
at com.mongodb.okr.App.main(App.java:28)
答案 0 :(得分:7)
JsonObject
类表示不可变 JSON对象值(一个 无序的零个或多个名称/值对的集合)。它也是 为JSON对象名称/值映射提供不可修改的映射视图。
您无法修改这些对象。
您需要创建副本。似乎没有直接的方法来做到这一点。您似乎需要使用Json.createObjectBuilder()
并自己构建它(请参阅链接的javadoc中的示例)。
答案 1 :(得分:0)
如Sotirios回答的那样,您可以使用JsonObjectBuilders。 要将值插入JsonObject,可以使用方法:
private JsonObject insertValue(JsonObject source, String key, String value) {
JsonObjectBuilder builder = Json.createObjectBuilder();
builder.add(key, value);
source.entrySet().
forEach(e -> builder.add(e.getKey(), e.getValue()));
return builder.build();
}
要将JsonObject插入JsonObject,可以使用方法:
private JsonObject insertObject(JsonObject parent, JsonObject child, String childName) {
JsonObjectBuilder child_builder = Json.createObjectBuilder();
JsonObjectBuilder parent_builder = Json.createObjectBuilder();
parent.entrySet().
forEach(e -> parent_builder.add(e.getKey(), e.getValue()));
child.entrySet().
forEach(e -> child_builder.add(e.getKey(), e.getValue()));
parent_builder.add(childName, child_builder);
return parent_builder.build();
}
请注意,如果在将子JsonObject插入另一个“父” JsonObject之后对其进行更改,则它将对“父” JsonObject无效。