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
🌐
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
Discussions

Why isEmpty( ) always returns true for jsonNode.get("some_key").isEmpty( )? Method isEmpty( ) works properly only if I add .asText( ) method: jsonNode.get("some_key").asText( ).isEmpty( );
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 More on reddit.com
🌐 r/javahelp
5
0
August 2, 2021
Jackson JsonNode with empty element key - Stack Overflow
I am using jackson-dataformat-xml (2.9) to parse an XML into JsonNode and then parse it to JSON (the XML is very dynamic so that is why I am using JsonNode instead of binding to a POJO. e.g 'elemen... More on stackoverflow.com
🌐 stackoverflow.com
May 26, 2020
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
spring - How to check JsonNode value is empty or not : java - Stack Overflow
I want to check Jsonnode value is present or not, As shown below myObj is an input. in this name is a key and "" is a value. I want to check if I get "" value then it should be ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
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.
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.
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.

🌐
Jenkov
jenkov.com › tutorials › java-json › jackson-jsonnode.html
Jackson JsonNode
To write a JsonNode into JSON with Jackson, you also need a Jackson ObjectMapper instance. On the ObjectMapper you call the writeValueAsString() method, or whatever write method that fits your needs. Here is an example of writing a JsonNode to JSON:
🌐
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 for missing nodes (trying to access missing property, or element at invalid item for array) or explicit nulls. ... Method that will try to convert value of this node to a Java int.
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 75156336 › how-to-check-jsonnode-value-is-empty-or-not-java
spring - How to check JsonNode value is empty or not : java - Stack Overflow
JsonNode myObj = {name:""}; JsonNode node = myObj.get("name"); if(node != null && !node.isNull()){ // do some things with the item node } else { // do something else } ... In java, JsonNode myObj = {name: ""}; is not a legal statement.
🌐
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.
🌐
Fasterxml
fasterxml.github.io › jackson-databind › javadoc › 2.6 › com › fasterxml › jackson › databind › JsonNode.html
JsonNode (jackson-databind 2.6.0 API) - FasterXML
Method similar to findValue(java.lang.String), but that will return a "missing node" instead of null if no field is found. Missing node is a specific kind of node for which isMissingNode() returns true; and all value access methods return empty or missing value. ... Value of first matching node found; or if not found, a "missing node" (non-null instance that has no value) public abstract JsonNode findParent(String fieldName)
🌐
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 ...
🌐
Adobe Developer
developer.adobe.com › experience-manager › reference-materials › 6-4 › javadoc › com › fasterxml › jackson › databind › JsonNode.html
JsonNode ("The Adobe AEM Quickstart and Web Application.")
Method for accessing all value nodes of this Node, iff this node is a JSON Array or Object node. In case of Object node, field names (keys) are not included, only values. For other types of nodes, returns empty iterator. public java.util.Iterator<java.util.Map.Entry<java.lang.String,JsonNode>> fields()
🌐
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
🌐
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)
Method for accessing all value nodes of this Node, iff this node is a JSON Array or Object node. In case of Object node, field names (keys) are not included, only values. For other types of nodes, returns empty iterator. public java.util.Iterator<java.util.Map.Entry<java.lang.String,​JsonNode>> fields()
🌐
Java Tips
javatips.net › api › com.fasterxml.jackson.databind.jsonnode
Java Examples for com.fasterxml.jackson.databind.JsonNode
Example 14 · @Override protected Result check() throws Exception { JsonNode json = mapper.readTree(new URL("http://pegelonline.wsv.de/webservices/rest-api/v2/stations.json").openStream()); if (!json.isArray()) return Result.unhealthy("pegelonline did not return JSON array"); if (json.size() == 0) return Result.unhealthy("pegelonline returned empty JSON"); return Result.healthy(); } Example 15 ·
🌐
Baeldung
baeldung.com › home › json › jackson › working with tree model nodes in jackson
Working with Tree Model Nodes in Jackson | Baeldung
January 8, 2024 - final String pathToTestFile = "node_to_json_test.json"; @Test public void givenANode_whenModifyingIt_thenCorrect() throws IOException { String newString = "{\"nick\": \"cowtowncoder\"}"; JsonNode newNode = mapper.readTree(newString); JsonNode rootNode = ExampleStructure.getExampleRoot(); ((ObjectNode) rootNode).set("name", newNode); assertFalse(rootNode.path("name").path("nick").isMissingNode()); assertEquals("cowtowncoder", rootNode.path("name").path("nick").textValue()); } The most convenient way to convert a JsonNode into a Java object is the treeToValue API:
🌐
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("{}");