使用javax/json,如何将元素添加到现有的JsonArray? [英] Using javax/json, how can I add elements to an existing JsonArray?

查看:82
本文介绍了使用javax/json,如何将元素添加到现有的JsonArray?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从文件中读取了一个JSON数组,但我想向该数组中添加其他条目.我将如何使用javax.json库执行此操作?

I read a JSON array from a file but I'd like to add additional entries into the array. How would I go about doing this using the javax.json library?

private String getJson(FileInputStream fis) throws IOException {
    JsonReader jsonReader = Json.createReader(fis);
    // Place where I'd like to get more entries.

    String temp = jsonReader.readArray().toString();
    jsonReader.close();
    fis.close();
    return temp;
}

文件JSON格式预览:

Preview of the JSON format of the file:

[
    {"imgOne": "test2.png", "imgTwo": "test1.png", "score": 123123.1},
    {"imgOne": "test2.png", "imgTwo": "test1.png", "score": 1234533.1}
]

推荐答案

简短的答案是你做不到. JsonArray (和其他值类型)为意味着一成不变. Javadoc声明

The short answer is that you can't. JsonArray (and the other value types) is meant to be immutable. The javadoc states

JsonArray表示一个不变的JSON数组( 零个或多个值).它还提供了不可修改的列表视图 数组中的值.

JsonArray represents an immutable JSON array (an ordered sequence of zero or more values). It also provides an unmodifiable list view of the values in the array.

长的答案是通过复制旧值和所需的任何新值来创建新的JsonArray对象.

The long answer is to create a new JsonArray object by copying over the values from the old one and whatever new values you need.

例如

// Place where I'd like to get more entries.
JsonArray oldArray = jsonReader.readArray();
// new array builder
JsonArrayBuilder builder = Json.createArrayBuilder();
// copy over old values
for (JsonValue value : oldArray) {
    builder.add(value);
}
// add new values
builder.add("new string value");
// done
JsonArray newArray = builder.build();

这篇关于使用javax/json,如何将元素添加到现有的JsonArray?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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