如何修改javax.json.JsonObject对象?

时间:2021-10-06 21:02:08

I am coding a feature in which I read and write back json. However I can read the json elements from a file but cant edit the same loaded object. Here is my code which I am working on.

我正在编写一个功能,我在其中读取和写回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 

    }

I get the following exception when I run it.

当我运行它时,我得到以下异常。

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)

1 个解决方案

#1


6  

The javadoc of JsonObject states

JsonObject的javadoc说明

JsonObject class represents an immutable JSON object value (an unordered collection of zero or more name/value pairs). It also provides unmodifiable map view to the JSON object name/value mappings.

JsonObject类表示不可变的JSON对象值(零个或多个名称/值对的无序集合)。它还为JSON对象名称/值映射提供了不可修改的映射视图。

You can't modify these objects.

您无法修改这些对象。

You'll need to create a copy. There doesn't seem to be a direct way to do that. It looks like you'll need to use Json.createObjectBuilder() and build it yourself (see the example in the javadoc linked).

您需要创建一个副本。似乎没有直接的方法来做到这一点。看起来你需要使用Json.createObjectBuilder()并自己构建它(参见链接的javadoc中的示例)。

#1


6  

The javadoc of JsonObject states

JsonObject的javadoc说明

JsonObject class represents an immutable JSON object value (an unordered collection of zero or more name/value pairs). It also provides unmodifiable map view to the JSON object name/value mappings.

JsonObject类表示不可变的JSON对象值(零个或多个名称/值对的无序集合)。它还为JSON对象名称/值映射提供了不可修改的映射视图。

You can't modify these objects.

您无法修改这些对象。

You'll need to create a copy. There doesn't seem to be a direct way to do that. It looks like you'll need to use Json.createObjectBuilder() and build it yourself (see the example in the javadoc linked).

您需要创建一个副本。似乎没有直接的方法来做到这一点。看起来你需要使用Json.createObjectBuilder()并自己构建它(参见链接的javadoc中的示例)。