简体   繁体   English

在javax.json.JsonArray中更改json元素的值

[英]change json elements' value in javax.json.JsonArray

[
    {
        "key":"key1",
        "value":"key one value",
        "description":""
    },
    {
        "key":"key2",
        "value":"key two value",
        "description":""
    },
    {
        "key":"key3",
        "value":"key three value",
        "description":""
    },
    {
        "key":"key4",
        "value":"key four value",
        "description":""
    },
    {
        "key":"key5",
        "value":"key five value",
        "description":""
    }   
]

This above is my an example json file I'm working with, I'm putting it into an JsonArray like this 这是我正在使用的示例json文件,我将其放入这样的JsonArray中

BufferedReader reader = Files.newBufferedReader(file,
                Charset.defaultCharset());
JsonReader jsonReader = Json.createReader(reader);
JsonArray array = jsonReader.readArray();

And My issue is I want to access the JsonArray and change the value part of each json element but is unable to do this. 我的问题是我想访问JsonArray并更改每个json元素的值部分,但无法执行此操作。 the collection doesn't seem to offer anyways to replace values of any json element. 无论如何,该集合似乎都无法提供替换任何json元素的值。 Do you know anyways I could achieve what I'm set to to do?? 无论如何,你知道我可以实现我的目标吗? PS: also open to suggestions on using an alternative collection, but please educate me on why should I choose said collection. 附言:也欢迎使用其他收藏夹的建议,但请教育我为什么要选择上述收藏夹。

Since you did not mention which JSON library you are using, you can use element method if you are using json-lib to replace an element 由于您没有提到要使用哪个JSON库,因此如果使用json-lib替换元素,则可以使用element方法

public JSONArray element(int index,
                         Object value)

If you want to update a specific attribute of the JSONObject element, you can try something like below 如果要更新JSONObject元素的特定属性,则可以尝试以下操作

array.getJSONObject(0).put("key","new key value")

Please note that I have used hard coded value 0 for demonstration purposes. 请注意,我已使用硬编码值0进行演示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM