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

🌐
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 }
🌐
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
🌐
Tabnine
tabnine.com › home page › code › java › com.fasterxml.jackson.databind.jsonnode
com.fasterxml.jackson.databind.JsonNode.isNull java code examples | Tabnine
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 ...
🌐
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("{}");
🌐
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.
🌐
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.
🌐
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 - 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 @JsonValue is used */ public class JsonNodeIssue { @JsonDeserialize(as = JsonDataImpl.class) public static interface Data { String getString(); } public static class JsonDataImpl implements Data { private final JsonNode jsonNode; @JsonCreator public JsonDataImpl(JsonNode jsonNode) { this.jsonNode = jsonNode; } @JsonValue public JsonNode getJsonNode() { return jsonNode; } @Override public String getString() { JsonNode string = jsonNode.get("string"); return string == null ?
Published   Nov 15, 2013
🌐
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);
🌐
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.
🌐
Javadoc.io
javadoc.io › static › com.fasterxml.jackson.core › jackson-databind › 2.10.1 › com › fasterxml › jackson › databind › JsonNode.html
JsonNode (jackson-databind 2.10.1 API)
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.
🌐
Oracle
docs.oracle.com › en › database › oracle › oracle-rest-data-services › 19.1 › ordjv › oracle › dbtools › plugin › api › json › objects › JSONNode.html
JSONNode (Oracle REST Data Services Java API Reference)
public interface JSONNode · Represents a JSONObject or JSONArray in a JSON document. Author: cdivilly · int size() The number of child elements in this node · Returns: The number of child elements of this node · boolean isEmpty() Indicates if this node has any child elements ·
🌐
Javadoc.io
javadoc.io › doc › com.fasterxml.jackson.core › jackson-databind › 2.0.6 › com › fasterxml › jackson › databind › JsonNode.html
JsonNode - jackson-databind 2.0.6 javadoc
Bookmarks · Latest version of com.fasterxml.jackson.core:jackson-databind · https://javadoc.io/doc/com.fasterxml.jackson.core/jackson-databind · Current version 2.0.6 · https://javadoc.io/doc/com.fasterxml.jackson.core/jackson-databind/2.0.6 · package-list path (used for javadoc generation ...