如何修改javax.json.JsonObject对象? [英] How to Modify a javax.json.JsonObject Object?

查看:694
本文介绍了如何修改javax.json.JsonObject对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个功能,我在其中读取和写回json。但是,我可以从文件中读取json元素,但无法编辑相同的加载对象。这是我正在处理的代码。

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.

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)


推荐答案

javadoc JsonObject 状态


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

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.

您无法修改这些对象。

You can't modify these objects.

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

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).

这篇关于如何修改javax.json.JsonObject对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆