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"
  } ]
}
Answer from Aleksand Kondaurov 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
🌐
Fasterxml
fasterxml.github.io › jackson-databind › javadoc › 2.6 › com › fasterxml › jackson › databind › JsonNode.html
JsonNode (jackson-databind 2.6.0 API) - FasterXML
isEmpty · clone, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait · asToken, numberType, traverse, traverse · forEach, spliterator · serialize, serializeWithType · protected JsonNode() public abstract <T extends JsonNode> T deepCopy() Method that can be called to get a node that is guaranteed not to allow changing of this node through mutators on this node or any of its children.
Discussions

How to test if JSON Collection object is empty in Java - Stack Overflow
Object getResult = obj.get("dps"); if (getResult != null && getResult instanceof java.util.Map && (java.util.Map)getResult.isEmpty()) { handleEmptyDps(); } else { handleResult(getResult); } ... @Test public void emptyJsonParseTest() { JsonNode emptyJsonNode = new ObjectMapper().createObjectNode(); ... More on stackoverflow.com
🌐 stackoverflow.com
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
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
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
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.

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.
🌐
Codota
codota.com › home page › code › java › com.fasterxml.jackson.databind.jsonnode
com.fasterxml.jackson.databind.JsonNode.isNull java code examples | Codota
List<String> getStringOrArray(Map<String, JsonNode> tree, String claimName) throws JWTDecodeException { JsonNode node = tree.get(claimName); if (node == null || node.isNull() || !(node.isArray() || node.isTextual())) { return null; } if (node.isTextual() && !node.asText().isEmpty()) { return Collections.singletonList(node.asText()); } List<String> list = new ArrayList<>(node.size()); for (int i = 0; i < node.size(); i++) { try { list.add(objectReader.treeToValue(node.get(i), String.class)); } catch (JsonProcessingException e) { throw new JWTDecodeException("Couldn't map the Claim's array contents to String", e); } } return list; } origin: Activiti/Activiti ·
🌐
Tabnine
tabnine.com › home page › code › java › com.fasterxml.jackson.databind.node.objectnode
com.fasterxml.jackson.databind.node.ObjectNode.isEmpty java code examples | Tabnine
ObjectNode objectNode = OBJECT_MAPPER.readTree(jp); if (!objectNode.isEmpty(null)) { T next = OBJECT_MAPPER.treeToValue(objectNode, clazz); log.trace("Monitor value: {}", next);
🌐
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
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 }
🌐
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)
isEmpty · clone, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait · forEach, spliterator · serialize, serializeWithType · asToken, numberType, traverse, traverse · protected JsonNode() public abstract <T extends JsonNode> T deepCopy() Method that can be called to get a node that is guaranteed not to allow changing of this node through mutators on this node or any of its children.
🌐
Baeldung
baeldung.com › home › json › jackson › difference between astext() and tostring() in jsonnode
Difference Between asText() and toString() in JsonNode | Baeldung
April 7, 2025 - (for example, due to sub-nodes): String json = "{\"name\":\"John\",\"age\":30}"; JsonNode node = new ObjectMapper().readTree(json); String name = node.get("name").asText(); assertThat(name).isEqualTo("John"); String age = node.get("age").asText(); ...
🌐
TutorialsPoint
tutorialspoint.com › how-can-we-check-if-a-json-object-is-empty-or-not-in-java
How can we check if a JSON object is empty or not in Java?\\n
import org.json.JSONObject; import org.json.JSONException; public class CheckEmptyJsonObjectExample { public static void main(String[] args) throws JSONException { // Create a JSON object JSONObject jsonObj = new JSONObject("{}"); // Check if the JSON object is empty or not if (jsonObj.isEmpty()) { System.out.println("JSON object is empty."); } else { System.out.println("JSON object is not empty."); } } }
🌐
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)
isEmpty · getClass, hashCode, notify, notifyAll, wait, wait, wait · forEach, spliterator · serialize, serializeWithType · asToken, numberType, traverse, traverse · public abstract <T extends JsonNode> T deepCopy() Method that can be called to get a node that is guaranteed not to allow changing of this node through mutators on this node or any of its children.
🌐
Unity
forum.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("{}");
🌐
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.