ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.createObjectNode();

or you can also do like you said in the comment above,

JsonNode node = JsonNodeFactory.instance.objectNode();

after that you can map the values,

JsonNode node = mapper.valueToTree(fromValue);
Answer from sanurah on Stack Overflow
Top answer
1 of 2
2
https://fasterxml.github.io/jackson-databind/javadoc/2.8/com/fasterxml/jackson/databind/JsonNode.html#get(java.lang.String) public JsonNode get(String fieldName) Method for accessing value of the specified field of an object node. If this node is not an object (or it does not have a value for specified field name), or if there is no field with such name, null is returned. NOTE: if the property value has been explicitly set as null (which is different from removal!), a NullNode will be returned, not null. https://fasterxml.github.io/jackson-databind/javadoc/2.8/com/fasterxml/jackson/databind/JsonNode.html#asText() public abstract String asText() Method that will return a valid String representation of the container value, if the node is a value node (method isValueNode() returns true), otherwise empty String. When you call isEmpty() on the result of asText() you are calling the String.isEmpty() https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#isEmpty() From what I can tell the JsonSerializable.Base class doesn't have an isEmpty() method only an isEmpty(SerializerProvider serializers) https://fasterxml.github.io/jackson-databind/javadoc/2.8/com/fasterxml/jackson/databind/JsonSerializable.Base.html
2 of 2
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 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. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar 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: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) 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.
Discussions

Generate an empty set of Json braces- using java & JSON - Stack Overflow
How to generate an empty json node using jackson-java. I tried with NullNode.instance, but that returns ... Whereas I want totals to be an empty instance. { "totals": {}, "orderId": "550047004", "numberOfItems": 2 } ... You should use ObjectNode. It can be created with ObjectMapper: ... Thanks! Just now I tried , new ObjectNode(JsonNodeFactory... More on stackoverflow.com
🌐 stackoverflow.com
July 21, 2018
Deserialization of empty JsonNode fails if @JsonValue is used
I'm not sure whether this is a defect, but I'm getting an exception when trying to de-serialize an empty "{}" object into a JsonNode when using @jsonvalue. Please see the code bel... More on github.com
🌐 github.com
2
November 15, 2013
Missing JsonNode field deserialized to null instead of NullNode
Describe the bug There's a behavior change between 2.12.6 and 2.13.0. Until then a missing JsonNode field was deserialized as a NullNode and it now is deserialized to Java null. Version informa... More on github.com
🌐 github.com
3
January 31, 2022
Add `isEmpty()` implementation for `JsonNode` serializers
Looks like empty (and default value) handling may not be implemented for JsonNode. It should, along with tests. More on github.com
🌐 github.com
2
January 14, 2015
🌐
GitHub
github.com › FasterXML › jackson-databind › issues › 2204
Add `JsonNode.isEmpty()` as convenience alias · Issue #2204 · FasterXML/jackson-databind
December 11, 2018 - An often-used idiom for checking for empty Arrays and Object for JsonNode is: if (arrayNode.size() == 0) { // is empty } and due to common use, would make sense to allow use via alias if (arrayNode.isEmpty()) { ... } Semantically it make...
Author   cowtowncoder
🌐
Fasterxml
fasterxml.github.io › jackson-core › javadoc › 1.9 › org › codehaus › jackson › node › NullNode.html
NullNode (Jackson JSON Processor) - FasterXML
Method that will return valid String representation of the container value, if the node is a value node (method JsonNode.isValueNode() returns true), otherwise empty String. Specified by: asText in class JsonNode · public int asInt(int defaultValue) Description copied from class: JsonNode · Method that will try to convert value of this node to a Java int.
🌐
Technicaldifficulties
technicaldifficulties.io › home › using jackson to remove empty json fields
Using Jackson to Remove Empty JSON Fields | Technical Difficulties
October 23, 2018 - * @param an object node * @return the object node with empty fields removed */ public static ObjectNode removeEmptyFields(final ObjectNode jsonNode) { ObjectNode ret = new ObjectMapper().createObjectNode(); Iterator<Entry<String, JsonNode>> iter = jsonNode.fields(); while (iter.hasNext()) { Entry<String, JsonNode> entry = iter.next(); String key = entry.getKey(); JsonNode value = entry.getValue(); if (value instanceof ObjectNode) { Map<String, ObjectNode> map = new HashMap<String, ObjectNode>(); map.put(key, removeEmptyFields((ObjectNode)value)); ret.setAll(map); } else if (value instanceof ArrayNode) { ret.set(key, removeEmptyFields((ArrayNode)value)); } else if (value.asText() != null && !value.asText().isEmpty()) { ret.set(key, value); } } return ret; } /** * Removes empty fields from the given JSON array node.
🌐
GitHub
github.com › FasterXML › jackson-databind › issues › 346
Deserialization of empty JsonNode fails if @JsonValue is used · Issue #346 · FasterXML/jackson-databind
November 15, 2013 - I'm not sure whether this is a defect, but I'm getting an exception when trying to de-serialize an empty "{}" object into a JsonNode when using @jsonvalue. Please see the code below: import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import java.io.IOException; /** * Deserialization of an empty JsonNode fails if @Js
Published   Nov 15, 2013
🌐
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 ...
Find elsewhere
🌐
Adobe Developer
developer.adobe.com › experience-manager › reference-materials › cloud-service › javadoc › com › fasterxml › jackson › databind › JsonNode.html
JsonNode (The Adobe Experience Manager SDK 2022.11.9850.20221116T162329Z-220900)
If no matching fields are found in this node or its descendants, returns an empty List. ... Similar to findValues(java.lang.String), but will additionally convert values into Strings, calling asText(). public abstract JsonNode findPath​(java.lang.String fieldName)
🌐
Tabnine
tabnine.com › home page › code › java › com.fasterxml.jackson.databind.jsonnode
com.fasterxml.jackson.databind.JsonNode.isNull java code examples | Tabnine
origin: auth0/java-jwt · String getString(Map<String, JsonNode> tree, String claimName) { JsonNode node = tree.get(claimName); if (node == null || node.isNull()) { return null; } return node.asText(null); } } origin: Activiti/Activiti ·
🌐
Fasterxml
fasterxml.github.io › jackson-databind › javadoc › 2.7 › com › fasterxml › jackson › databind › JsonNode.html
JsonNode (jackson-databind 2.7.0 API)
Method that will return a valid String representation of the container value, if the node is a value node (method isValueNode() returns true), otherwise empty String. ... Method similar to asText(), except that it will return defaultValue in cases where null value would be returned; either ...
🌐
GitHub
github.com › FasterXML › jackson-databind › issues › 3389
Missing JsonNode field deserialized to null instead of NullNode · Issue #3389 · FasterXML/jackson-databind
January 31, 2022 - Describe the bug There's a behavior change between 2.12.6 and 2.13.0. Until then a missing JsonNode field was deserialized as a NullNode and it now is deserialized to Java null. Version information Behavior change occurs since 2.13.0 To ...
Author   the8tre
🌐
GitHub
github.com › codehaus › jackson › blob › master › src › java › org › codehaus › jackson › JsonNode.java
jackson/src/java/org/codehaus/jackson/JsonNode.java at master · codehaus/jackson
List<JsonNode> result = findValues(fieldName, null); if (result == null) { return Collections.emptyList(); } return result; } · /** * Similar to {@link #findValues}, but will additionally convert · * values into Strings, calling {@link #getValueAsText}. * ·
Author   codehaus
🌐
GitHub
github.com › FasterXML › jackson-databind › issues › 679
Add `isEmpty()` implementation for `JsonNode` serializers · Issue #679 · FasterXML/jackson-databind
January 14, 2015 - Looks like empty (and default value) handling may not be implemented for JsonNode. It should, along with tests.
Author   cowtowncoder
🌐
Unity
discussions.unity.com › unity engine
How to create a empty JSONNode? - Unity Engine - Unity Discussions
August 18, 2019 - I’m having problems figuring out how to create a empty JSON Node If i give it a parse empty bracket string like this it works. Gotta be another way? JSONNode m_JSONNode = JSON.Parse("{}");
🌐
Javadoc.io
javadoc.io › doc › com.fasterxml.jackson.core › jackson-databind › 2.10.2 › com › fasterxml › jackson › databind › JsonNode.html
JsonNode - jackson-databind 2.10.2 javadoc
Bookmarks · Latest version of com.fasterxml.jackson.core:jackson-databind · https://javadoc.io/doc/com.fasterxml.jackson.core/jackson-databind · Current version 2.10.2 · https://javadoc.io/doc/com.fasterxml.jackson.core/jackson-databind/2.10.2 · package-list path (used for javadoc generation ...
Top answer
1 of 4
2

I figured out that this behaviour can be achieved via configuration. Here is the kotlin code but it's simple to convert to java Just create xmlMapper with appropriate configuration

    fun jacksonCreateXmlMapper(): XmlMapper {
        val module = JacksonXmlModule()
        module.setXMLTextElementName("value")
        return XmlMapper(module)
    }

For input

<products>
    <product count="5">apple</product>
    <product count="10">orange</product>
</products>

you get:

{
  "product" : [ {
    "count" : "5",
    "value" : "apple"
  }, {
    "count" : "10",
    "value" : "orange"
  } ]
}
2 of 4
1

You also could simply post-process the JSON DOM, traverse to all objects, and rename the keys that are empty strings to "value".

Race condition: such a key may already exist, and must not be overwritten
(e.g. <id type="pid" value="existing">abcdef123</id>).

Usage:
(note: you should not silently suppress the exception and return null, but allow it to propagate so the caller can decide to catch and apply failover logic if required)

public InputStream parseXmlResponse(InputStream xmlStream) throws IOException {
    JsonNode node = xmlMapper.readTree(xmlStream);
    postprocess(node);
    return new ByteArrayInputStream(jsonMapper.writer().writeValueAsBytes(node));
}

Post-processing:

private void postprocess(JsonNode jsonNode) {

    if (jsonNode.isArray()) {
        ArrayNode array = (ArrayNode) jsonNode;
        Iterable<JsonNode> elements = () -> array.elements();

        // recursive post-processing
        for (JsonNode element : elements) {
            postprocess(element);
        }
    }
    if (jsonNode.isObject()) {
        ObjectNode object = (ObjectNode) jsonNode;
        Iterable<String> fieldNames = () -> object.fieldNames();

        // recursive post-processing
        for (String fieldName : fieldNames) {
            postprocess(object.get(fieldName));
        }
        // check if an attribute with empty string key exists, and rename it to 'value',
        // unless there already exists another non-null attribute named 'value' which
        // would be overwritten.
        JsonNode emptyKeyValue = object.get("");
        JsonNode existing = object.get("value");
        if (emptyKeyValue != null) {
            if (existing == null || existing.isNull()) {
                object.set("value", emptyKeyValue);
                object.remove("");
            } else {
                System.err.println("Skipping empty key value as a key named 'value' already exists.");
            }
        }
    }
}

Output: just as expected.

{
   "elementName": {
     "id": {
        "type": "pid",
        "value": "abcdef123"
     }
   },
}

EDIT: considerations on performance:

I did a test with a large XML file (enwikiquote-20200520-pages-articles-multistream.xml, en.wikiquote XML dump, 498.4 MB), 100 rounds, with following measured times (using deltas with System.nanoTime()):

  • average read time (File, SSD): 2870.96 ms
    (JsonNode node = xmlMapper.readTree(xmlStream);)
  • average postprocessing time: 0.04 ms
    (postprocess(node);)
  • average write time (memory): 0.31 ms
    (new ByteArrayInputStream(jsonMapper.writer().writeValueAsBytes(node));)

That's a fraction of a millisecond for an object tree build from a ~500 MB file - so performance is excellent and no concern.

🌐
GitHub
github.com › FasterXML › jackson-1 › blob › master › src › java › org › codehaus › jackson › JsonNode.java
jackson-1/src/java/org/codehaus/jackson/JsonNode.java at master · FasterXML/jackson-1
List<JsonNode> result = findValues(fieldName, null); if (result == null) { return Collections.emptyList(); } return result; } · /** * Similar to {@link #findValues}, but will additionally convert · * values into Strings, calling {@link #getValueAsText}. * ·
Author   FasterXML
🌐
Red Hat
access.redhat.com › webassets › avalon › d › red_hat_jboss_enterprise_application_platform › 8.0 › javadocs › com › fasterxml › jackson › databind › JsonNode.html
JsonNode (Red Hat JBoss Enterprise Application Platform 8.0.0.GA public API)
Method that will return a valid String representation of the container value, if the node is a value node (method isValueNode() returns true), otherwise empty String. ... Method similar to asText(), except that it will return defaultValue in cases where null value would be returned; either ...