So what you have is a JSON object, so JsonNode.Parse will really return a JsonObject, so first we need to cast it:

var jsonObject = JsonNode.Parse(input)!.AsObject(); // null check omitted for brevity

Now let's do the rename. A rename is really a removal of the object with the old property followed by readding it with the new name. So:

var node = jsonObject["foo"]; // take a reference to foo so we don't lose it
jsonObject.Remove("foo"); // detach from parent
jsonObject.Add("bar", node); // attach with new name

The reason why you need to first remove it and then add it back, is that JsonNode objects have parents, and you're not allowed to add a node to an object or array if it already has a parent. So you first need to detach it from its parent with Remove, and then you can add it back under the new name with Add.

Now, this modifies the original JSON object. If you want to instead keep the original intact you'll have to clone it first. This is a problem, because there is no way to clone a JsonNode. You could do this:

var clone = new JsonObject(jsonObject);

And it will compile, but then at runtime you'll hit an exception because this just adds the nodes from one object to the next and as we've already established you can't add an object that already has a parent to another one. You would have to first clone each child node and add those instead.

As far as I'm aware, the JsonNodes namespace has no way to do a deep clone of JSON nodes. It seems like an oversight. You could either do it by hand by recursively enumerating the nodes in the document and creating them, or just parse the document twice.

Answer from Etienne de Martel on Stack Overflow
🌐
DEV Community
dev.to › vparab › working-with-jsonobject-jsonnode-jsonvalue-and-jsonarray-systemtextjson-api-5b8l
Working with JsonObject, JsonNode, JsonValue and JsonArray [System.Text.Json API] - DEV Community
May 23, 2024 - On JsonNode, we can call AsValue(), AsArray() and AsObject() to get the corresponding type. Next, we could also assert the kind through GetValueKind and call any one of the factory methods we saw earlier to retrieve our value.
🌐
Unity
discussions.unity.com › unity engine
Convert JSONNode to JSON - Unity Engine - Unity Discussions
July 29, 2018 - Anyone know how to convert JSONNode back to JSON · If you’re using http://wiki.unity3d.com/index.php/SimpleJSON, then you just call ToString() · Thanks for the reply villevli. Ya I tried that last night and then when I converter it back and tried to get a value from it it return null.
Discussions

Working with jsonnode class
Working with JsonNode class. Is there any function or property to get the various key value pairs? Would jsonDocument be better? I have a string I got from an http request and I need to manipulate the data. One example of the json is below. all other entries are similar. More on answeroverflow.com
🌐 answeroverflow.com
October 12, 2023
Does it consider a bad practice to use jsonNode as the return type
Normally devs prefer to have a POJO/DTO class dedicated for your specific domain model. And when you de-serialize your JSON you don't use JsonNode, but your specific type. Like this: try { Book book = new ObjectMapper().readValue(jsonString, Book.class); } catch (JsonProcessingException e) { // do something when it goes wrong } This approach has some benefits, for example: immediately getting an exception if your JSON has wrong or not matching structure having a proper POJO gives you all OOP benefits, including your custom methods in your class, getters, setters and so on JsonNode is used when you're processing something super generic or unexpected, so you're not sure what structure this JSON has and you prefer to have a "safe" container, not giving you any exceptions. As for ResponseEntity - It's a common practice to have it as a return type from you REST controllers, with some typisation normally, like ResponseEntity for example. You wrapping ResponseEntity object into another object - DeferredResult, it makes no sense. Probably, makes sense to do it other way around - ResponseEntity, but it's hard to say not knowing your logic or domain model. Why do you want ResponceEntity as your controller return type? this class purpose is exactly this - wrap your response object into handy class with all HTTP things embedded you can easily configure your HTTP status and headers with this class in has a lot of methods and builders to do it in a concise manner More on reddit.com
🌐 r/learnjava
11
4
June 14, 2024
Conversion between JsonElement and JsonNode
Hey everyone, I have a question: the original writable DOM design had dedicated APIs to convert JsonElement from and to JsonNode instances. I don't see an equivalent in the recent implementatio... More on github.com
🌐 github.com
10
May 11, 2021
jackson - How to get JSON Object from JSONNode Array? - Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most. Learn more about Collectives ... Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... I wish to get the ObjectIWantToRetrieve out The equivalent of JsonNode.get... More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 2
14

So what you have is a JSON object, so JsonNode.Parse will really return a JsonObject, so first we need to cast it:

var jsonObject = JsonNode.Parse(input)!.AsObject(); // null check omitted for brevity

Now let's do the rename. A rename is really a removal of the object with the old property followed by readding it with the new name. So:

var node = jsonObject["foo"]; // take a reference to foo so we don't lose it
jsonObject.Remove("foo"); // detach from parent
jsonObject.Add("bar", node); // attach with new name

The reason why you need to first remove it and then add it back, is that JsonNode objects have parents, and you're not allowed to add a node to an object or array if it already has a parent. So you first need to detach it from its parent with Remove, and then you can add it back under the new name with Add.

Now, this modifies the original JSON object. If you want to instead keep the original intact you'll have to clone it first. This is a problem, because there is no way to clone a JsonNode. You could do this:

var clone = new JsonObject(jsonObject);

And it will compile, but then at runtime you'll hit an exception because this just adds the nodes from one object to the next and as we've already established you can't add an object that already has a parent to another one. You would have to first clone each child node and add those instead.

As far as I'm aware, the JsonNodes namespace has no way to do a deep clone of JSON nodes. It seems like an oversight. You could either do it by hand by recursively enumerating the nodes in the document and creating them, or just parse the document twice.

2 of 2
1

Your question update adds "bar" to an existing node object. if you want to create a new object that is a copy of an existing node object, you can make it 2 main ways

  1. The simpliest and most efficient way is to change json string
    string newInput = input.Replace("\"foo\":","\"bar\":");
    var newNode=JsonNode.Parse(newInput);
  1. Or create new json object
var newNode = new JsonObject( new[] { KeyValuePair.Create<string,JsonNode>("bar", 
               JsonNode.Parse(node["foo"].ToJsonString()) )});

result

{
  "bar": [
    {
      "a": 1
    },
    {
      "b": null
    }
  ]
}
🌐
C# Corner
c-sharpcorner.com › article › new-programming-model-for-handling-json-in-net-6
New Programming Model For Handling JSON In .NET 6
June 1, 2023 - You can easily navigate to sections of the JSON structure. Also, You can use LINQ. Allow use of dynamic keyword, like dynamic obj = JsonNode.Parse(“my_json_object”) Create a JSON Object using JsonObject Class.
🌐
Makolyte
makolyte.com › csharp-how-to-use-jsonnode-to-read-write-and-modify-json
C# - How to use JsonNode to read, write, and modify JSON | makolyte
January 26, 2025 - You can use JsonNode to write JSON from scratch. This is a nice alternative to having raw JSON strings in the code. You can add values, arrays (via JsonArray), and objects (via JsonObject) using the familiar object initializer syntax:
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › system.text.json.nodes.jsonnode
JsonNode Class (System.Text.Json.Nodes) | Microsoft Learn
Microsoft makes no warranties, express or implied, with respect to the information provided here. The base class that represents a single node within a mutable JSON document. public ref class JsonNode abstract · public abstract class JsonNode · type JsonNode = class · Public MustInherit Class JsonNode · Inheritance · Object JsonNode · Derived · System.Text.Json.Nodes.JsonArray · System.Text.Json.Nodes.JsonObject ·
🌐
Answer Overflow
answeroverflow.com › m › 1162019695176724541
Working with jsonnode class - C#
October 12, 2023 - { "LicenseUsageList": [ { "UserName": "doman\\username", "LicenseType": "license type", "AcquisitionTime": "2023-10-12T08:04:52.523", "SessionType": "UISERVER-FULL", "SessionId": "session id", "LicenseProperties": [ { "Key": "DbServerPid", "Value": "64" }, { "Key": "ProgramName", "Value": "program name" }, { "Key": "DbExecutionContextId", "Value": "0" }, { "Key": "Name", "Value": "app name" }, { "Key": "LoginName", "Value": "user name" }, { "Key": "LoginTime", "Value": "10/12/2023 08:04:52" }, { "Key": "HostName", "Value": "server name" }, { "Key": "HostPid", "Value": "hostPid" } ] }, ] } I'd like to access each node via the "UserName" property and find duplicate values · C#JoinWe are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
Find elsewhere
🌐
Reddit
reddit.com › r/learnjava › does it consider a bad practice to use jsonnode as the return type
r/learnjava on Reddit: Does it consider a bad practice to use jsonNode as the return type
June 14, 2024 -

I am a beginner of Java & Springboot. I feel like I am doing something that does not use the full strength of spring boot, e.g. using JsonNode & return untyped Response Entity etc.

Just wonder if there is any best practice when dealing with this kind of situation, when I want to return an object as part of result.

In Typescript I can create an interface for the object, how about in java / Springboot?

TestService.java

...
@Service
@Slf4j
public class TestService {
    private final TsKvRepository tsKvRepository;
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    public TestService(TsKvRepository tsKvRepository) {
        this.tsKvRepository = tsKvRepository;
    }

    public DeferredResult<ResponseEntity> getLatestTimeseries(String entityIdStr, String eui64) {
        DeferredResult<ResponseEntity> result = new DeferredResult<>();

        try {
            UUID entityId = UUID.fromString(entityIdStr);
            List<TsKvEntity> tsList =  this.tsKvRepository.findLatestByEui64(entityId, eui64);

            if (!tsList.isEmpty()) {
                TsKvEntity tsKvEntity = tsList.get(0);
                JsonNode jsonNode = objectMapper.readTree(tsKvEntity.getJsonValue());
                
                ResponseEntity<?> responseEntity = new ResponseEntity<>(jsonNode.get(0), HttpStatus.OK);
                result.setResult(responseEntity);
            } else {
                ResponseEntity<?> responseEntity = new ResponseEntity<>("No data found", HttpStatus.NOT_FOUND);
                result.setResult(responseEntity);
            }

        }catch(IllegalArgumentException | NullPointerException e) {
            ResponseEntity<?> responseEntity = new ResponseEntity<>("Invalid UUID format or null keysStr: " + e.getMessage(), HttpStatus.BAD_REQUEST);
            result.setResult(responseEntity);
        } catch (JsonMappingException e) {
            throw new RuntimeException(e);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return result;
    }

}
Top answer
1 of 3
8
Normally devs prefer to have a POJO/DTO class dedicated for your specific domain model. And when you de-serialize your JSON you don't use JsonNode, but your specific type. Like this: try { Book book = new ObjectMapper().readValue(jsonString, Book.class); } catch (JsonProcessingException e) { // do something when it goes wrong } This approach has some benefits, for example: immediately getting an exception if your JSON has wrong or not matching structure having a proper POJO gives you all OOP benefits, including your custom methods in your class, getters, setters and so on JsonNode is used when you're processing something super generic or unexpected, so you're not sure what structure this JSON has and you prefer to have a "safe" container, not giving you any exceptions. As for ResponseEntity - It's a common practice to have it as a return type from you REST controllers, with some typisation normally, like ResponseEntity for example. You wrapping ResponseEntity object into another object - DeferredResult, it makes no sense. Probably, makes sense to do it other way around - ResponseEntity, but it's hard to say not knowing your logic or domain model. Why do you want ResponceEntity as your controller return type? this class purpose is exactly this - wrap your response object into handy class with all HTTP things embedded you can easily configure your HTTP status and headers with this class in has a lot of methods and builders to do it in a concise manner
2 of 3
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
🌐
Baeldung
baeldung.com › home › json › jackson › how to convert jsonnode to objectnode
How to Convert JsonNode to ObjectNode | Baeldung
June 21, 2025 - ObjectNode can be defined as a mutable subclass of JsonNode that specifically represents an object node. It allows the manipulation of these types of objects by providing methods to add, remove, and modify key-value pairs within the object.
🌐
GitHub
github.com › dotnet › runtime › issues › 52611
Conversion between JsonElement and JsonNode · Issue #52611 · dotnet/runtime
May 11, 2021 - Hey everyone, I have a question: the original writable DOM design had dedicated APIs to convert JsonElement from and to JsonNode instances. I don't see an equivalent in the recent implementatio...
Published   May 11, 2021
Author   kevinchalet
🌐
GitHub
github.com › ebassi › json-glib › blob › master › json-glib › json-node.c
json-glib/json-glib/json-node.c at master · ebassi/json-glib
* If the node has already been initialized once, it will be reset to · * the given type, and any data contained will be cleared. * * Return value: (transfer none): the initialized #JsonNode · * * Since: 0.16 · */ JsonNode * json_node_init_object (JsonNode *node, JsonObject *object) { g_return_val_if_fail (node != NULL, NULL); ·
Author   ebassi
🌐
Jenkov
jenkov.com › tutorials › java-json › jackson-jsonnode.html
Jackson JsonNode
The Jackson JsonNode class is the Jackson tree object model for JSON. Jackson can read JSON into an object graph (tree) of JsonNode objects. Jackson can also write a JsonNode tree to JSON. This Jackson JsonNode tutorial explains how to work with the Jackson JsonNode class and its mutable subclass ObjectNode.
🌐
Raspberry Pi Forums
forums.raspberrypi.com › board index › programming › c/c++
What am I doing wrong with JSON? - Raspberry Pi Forums
Node* readTreeFromFile(FILE* bestand) ... = json_tokener_parse(buffer); if(jsonObject == NULL) { printf("Fout bij het parsen van JSON!\n"); free(buffer); return NULL; } Node* rootNode = parseJSONNode(jsonObject); json_object_put(jsonObject); free(buffer); return rootNode; } Node* parseJSONNode(struct json_object* jsonNode) { Node* node = malloc(sizeof(Node)); node->ja = NULL; node->nee = NULL; struct json_object* typeObject; if(json_object_object_get_ex(jsonNode, "type", &typeObject)) { const char* typeString ...
🌐
Kevsoft
kevsoft.net › 2021 › 12 › 29 › manipulate-json-with-system-text-json-nodes.html
Manipulate JSON with System.Text.Json.Nodes - Developer Ramblings of Kevin Smith
December 29, 2021 - Similar to our JsonObject in the last section, a JsonArray can be created in a same way. There’s a constructor that takes in an array of JsonNodes.
🌐
GitHub
github.com › frida › json-glib › blob › main › json-glib › json-object.c
json-glib/json-glib/json-object.c at main · frida/json-glib
* Seals the object, making it immutable to further changes. * * This function will recursively seal all members of the object too. * * If the object is already immutable, this is a no-op. * * Since: 1.2 · */ void · json_object_seal (JsonObject *object) { JsonObjectIter iter; JsonNode *node; ·
Author   frida
🌐
Baeldung
baeldung.com › home › json › jackson › working with tree model nodes in jackson
Working with Tree Model Nodes in Jackson | Baeldung
January 8, 2024 - In this tutorial, we'll see how to orchestrate a multi-step flow for a ride-hailing application by integrating Dapr Workflows and Spring Boot: ... This tutorial will focus on working with tree model nodes in Jackson. We’ll use JsonNode for various conversions as well as adding, modifying, and removing nodes.
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › system.text.json.nodes.jsonnode.tojsonstring
JsonNode.ToJsonString(JsonSerializerOptions) Method (System.Text.Json.Nodes) | Microsoft Learn
Access to this page requires authorization. You can try changing directories. Summarize this article for me · Namespace: System.Text.Json.Nodes · Assembly: System.Text.Json.dll · Package: System.Text.Json v11.0.0-preview.1.26104.118 · Source: JsonNode.To.cs ·