简体   繁体   中英

Java - Add List Of Objects Inside JSON Array

I have a list of option class, I want a way to convert the all option inside list into Json and add them to the array inside the simple Json file below.

I'm using play framework, So I have to use its Json library.

I have read the file and get the options node after loop over all nodes by:

jsonNode.get("options")

and it is return an object of type com.fasterxml.jackson.databind.JsonNode

this an explain code:

List<Option> options = new ArrayList<>();

Option class:

public class Option {
    private String key;
    private String query;
    private String display;
}

Json File:

    "options": [
        {
            "key": "...",
            "query": "...",
            "display": "..."
        },
        {
            "key": "...",
            "query": "...",
            "display": "..."
        },...
    ]

It is just i can't figure a way to add all option from the List inside the Json file tag options , Can anyone help?

First I have get all options by:

    List<FacetOption> nodeOptions = mapper.treeToValue(jsonNode.get("options"), List.class);

Then, add all new option list to current node list:

    nodeOptions.addAll(options);

Then, replace old node inside JsonNode :

    ObjectNode objectNode = (ObjectNode) jsonNode;
    objectNode.replace("options", Json.toJson(nodeOptions)); 

Finally, write the new file I need:

mapper.writeValue(new File(newJsonFilePath), rootNode);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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