In Jackson 2.4, you can convert as follows:

MyClass newJsonNode = jsonObjectMapper.treeToValue(someJsonNode, MyClass.class);

where jsonObjectMapper is a Jackson ObjectMapper.


In older versions of Jackson, it would be

MyClass newJsonNode = jsonObjectMapper.readValue(someJsonNode, MyClass.class);
Answer from icedtrees on Stack Overflow
Discussions

java - Convert JsonNode into Object - Stack Overflow
But I'm not very happy with this ... my JsonNode into a String representation before it is deserialized into a POJO. The performance is an issue for me in this case. ... Well, you could query the node to see what type it is and then deal with it as its "real" type. And, if necessary, write a MyObject(jsonObject object) constructor ... More on stackoverflow.com
🌐 stackoverflow.com
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
java - How to convert JsonNode to ObjectNode - Stack Overflow
I have a com.fasterxml JsonNode object with some data. I need to do some manipulation on its data. I googled for answer but didn't got it properly. Can you please suggest me how to manipulate JsonN... More on stackoverflow.com
🌐 stackoverflow.com
How to convert JsonNode to ObjectNode
I want to partly modify some field value in a json file without entity class , so i have to use JsonNode to convert to ObjectNode. More on github.com
🌐 github.com
1
December 10, 2018
🌐
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.
🌐
Attacomsian
attacomsian.com › blog › jackson-convert-java-object-to-json-node
Convert Java Object to JsonNode using Jackson
October 14, 2022 - To convert an instance of JsonNode to a Java Object, you can use the treeToValue() method from ObjectMapper:
🌐
Fasterxml
fasterxml.github.io › jackson-databind › javadoc › 2.7 › com › fasterxml › jackson › databind › JsonNode.html
JsonNode (jackson-databind 2.7.0 API)
public abstract class JsonNode extends JsonSerializable.Base implements TreeNode, Iterable<JsonNode> Base class for all JSON nodes, which form the basis of JSON Tree Model that Jackson implements. One way to think of these nodes is to consider them similar to DOM nodes in XML DOM trees. As a general design rule, most accessors ("getters") are included in this base class, to allow for traversing structure without type casts. Most mutators, however, need to be accessed through specific sub-classes (such as ObjectNode and ArrayNode).
🌐
TutorialsPoint
tutorialspoint.com › jackson › jackson_tree_to_object.htm
Jackson - Tree to Java Objects
package com.tutorialspoint; import java.io.File; import java.io.IOException; import java.util.Arrays; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; public class JacksonTester { public static void main(String args[]){ try { ObjectMapper mapper = new ObjectMapper(); JsonNode rootNode = mapper.createObjectNode(); JsonNode ma
Find elsewhere
🌐
Baeldung
baeldung.com › home › json › jackson › working with tree model nodes in jackson
Working with Tree Model Nodes in Jackson | Baeldung
January 8, 2024 - The most convenient way to convert a JsonNode into a Java object is the treeToValue API:
🌐
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.
🌐
GitHub
github.com › FasterXML › jackson-databind › issues › 2199
How to convert JsonNode to ObjectNode · Issue #2199 · FasterXML/jackson-databind
December 10, 2018 - I want to partly modify some field value in a json file without entity class , so i have to use JsonNode to convert to ObjectNode. but when i attempt to do this way, it throw a exception:Caused by: java.lang.ClassCastException: com.faste...
Author   mk100120
🌐
Stack Overflow
stackoverflow.com › questions › 34786342 › jsonnode-to-object
java - JsonNode to object? - Stack Overflow
April 26, 2017 - Leave it as an object. Jackson automatically pick the right type in runtime. Later based on the name you can convert it to the right type. ... public class AttributeDeserializer extends JsonDeserializer<Attribute> { @Override public Attribute deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { JsonNode node = jp.getCodec().readTree(jp); String longName = getLongName(node.get("name").asText()); System.out.println("Translated name: " + name); ObjectMapper objMapper = new ObjectMapper(); ObjectNode o = (ObjectNode)node; o.put("name", name); Attribute attr = objMapper.convertValue(o, Attribute.class); return attr; } }
🌐
Medium
medium.com › @salvipriya97 › jsonnode-explained-with-examples-d0c05324f61d
JsonNode explained with examples. What is JsonNode in Java? | by Priya Salvi | Medium
July 2, 2024 - Serialization: The transformed JsonNode is serialized back into a JSON string using ObjectMapper.writeValueAsString(). JsonNode is a powerful tool in Java for working with JSON data dynamically and flexibly.
🌐
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 ·
🌐
Java Code Geeks
javacodegeeks.com › home › core java
Jackson JsonNode to Java Collections - Java Code Geeks
July 8, 2024 - Here we read a JSON string into a JsonNode and then convert it into a Map<String, Object> and a List<Map<String, Object>>. This method is straightforward and leverages Jackson’s type handling to automatically convert the JsonNode to the desired ...
🌐
Medium
cowtowncoder.medium.com › jackson-tips-objectnode-putpojo-putrawvalue-for-fun-and-profit-358f8f3b8580
Jackson Tips: ObjectNode.putPOJO(), putRawValue() for fun and profit | by @cowtowncoder | Medium
September 29, 2021 - Jackson library allows use of all kinds of Java object types to represent JSON data to read and write: from java.util.Maps, java.util.Collection s and arrays to “Plain Old Java Object” (POJOs, aka Beans), as well as most scalar JDK types (Strings, Numbers, Booleans, Date/Time values). But equally importantly Jackson provides its own “Tree Model”: a node-based representation where JSON values are represented by various sub-types of JsonNode base type — ObjectNode for JSON Objects, ArrayNode for JSON Arrays, TextNode for JSON Strings and so on.
🌐
Baeldung
baeldung.com › home › json › jackson › jackson – marshall string to jsonnode
Jackson - Marshall String to JsonNode | Baeldung
June 28, 2023 - @Test public void whenParsingJsonStringIntoJsonNode_thenCorrect() throws JsonParseException, IOException { String jsonString = "{\"k1\":\"v1\",\"k2\":\"v2\"}"; ObjectMapper mapper = new ObjectMapper(); JsonNode actualObj = mapper.readTree(jsonString); assertNotNull(actualObj); } If, for some reason, you need to go lower level than that, the following example exposes the JsonParser responsible with the actual parsing of the String:
🌐
GitHub
gist.github.com › diegoicosta › f06f61720f02b8c00afddb146ade5cce
Using Jackson to create manually a JsonNode · GitHub
Using Jackson to create manually a JsonNode. GitHub Gist: instantly share code, notes, and snippets.