简体   繁体   中英

how to add attribute at any place in json using JsonObject in java

I have a json. Lets say:

{
 "id":"101",
 "name":"Saurabh",
 "age":"28"
}

Now, I want to add "rollNo":"52" just after id attribute. How can I do that using jsonNode in java?

Actually I am parsing this object using jsonNode, so no pojo mapping I just want a way to add the attribute anywhere with creating a pojo mapping.

JsonNode is immutable and is intended for parse operation. However, it can be cast into ObjectNode and add value ((ObjectNode)jsonNode).put("rollNo", "52");

JSON properties are not ordered. You cannot decide to put one "just after" another. They will be in the order they will be.

Well, that's how it's meant. If you use a Jackson streaming JSON Writer, you can use it to write the properties in the order you like. But that's jumping through hoops just to do something that you shouldn't want to do in the first place. When you want stuff in a specific order, put them in arrays.

I actually found a way to do that.

First create a new blank node, then iterate over original node and check your condition and put the new node accordingly. This may take only fraction of time, but will resolve these kind of issues.

Here is the code

ObjectNode newChildNode = new ObjectNode(JsonNodeFactory.instance);
Iterator<Map.Entry<String, JsonNode>> fields = childNode.fields();
while(fields.hasNext()){
    Map.Entry<String, JsonNode> entry = fields.next();
    newChildNode.putPOJO(entry.getKey(), entry.getValue());
    if("id".equals(entry.getKey())){
        newChildNode.put("rollNo", "52");
    }
}

//This will convert the POJO Node again to JSON node
ObjectMapper mapper = new ObjectMapper();
newChildNode= mapper.readTree(newChildNode.toString());

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