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
🌐
Jenkov
jenkov.com › tutorials › java-json › jackson-jsonnode.html
Jackson JsonNode
Let me just spend a moment to explore how you handle null values in the Jackson JsonNode. There are two ways in which a field inside a JsonNode can be null. The first way is, if the field is completely missing from the JSON from which the JsonNode was created. Here is an example of a simple JSON string that only contains a single field:
🌐
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.
🌐
Apps Developer Blog
appsdeveloperblog.com › home › java › java json › modify jsonnode with java jackson
Modify JsonNode with Java Jackson - Apps Developer Blog
August 12, 2022 - To see where to find Jackson jars, read Introduction to Java JSON. The JsonNode class is immutable. That means we cannot modify it. For that purpose, we can use the ObjectNode, which is the subclass of the JsonNode. In this lesson, we will cover adding and removing a field from the JsonNode. Since we can not modify the JsonNode, we first need to cast it to the ObjectNode. Let’s create an empty ...
🌐
Baeldung
baeldung.com › home › json › jackson › working with tree model nodes in jackson
Working with Tree Model Nodes in Jackson | Baeldung
January 8, 2024 - This is the most common way to create a node out of nothing: ... This method is well covered in the Jackson – Marshall String to JsonNode article.
🌐
DEV Community
dev.to › sadiul_hakim › jackson-tutorial-comprehensive-guide-with-examples-2gdj
Jackson Tutorial: Comprehensive Guide with Examples - DEV Community
September 18, 2025 - import com.fasterxml.jackson.d...e.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; ObjectMapper mapper = new ObjectMapper(); // Create an empty object node ObjectNode personNode = mapper.createObjectNode(); ...
🌐
Fasterxml
fasterxml.github.io › jackson-core › javadoc › 1.9 › org › codehaus › jackson › node › NullNode.html
NullNode (Jackson JSON Processor) - FasterXML
Method that can be used to check if this node was created from Json liternal null value. Overrides: isNull in class JsonNode · public String asText() Description copied from class: JsonNode · 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.
Find elsewhere
🌐
Attacomsian
attacomsian.com › blog › jackson-json-node-tree-model
Working with Tree Model Nodes in Jackson
October 14, 2022 - Finally, the last way to create a new JsonNode is converting a Java Object by using the valueToTree() method from ObjectMapper: // create user object User user = new User("John Doe", "john.doe@example.com", new String[]{"Member", "Admin"}, true); // ...
🌐
Makeseleniumeasy
makeseleniumeasy.com › 2020 › 05 › 16 › rest-assured-tutorial-27-how-to-create-json-array-using-jackson-api-objectmapper-createarraynode
REST Assured Tutorial 27 – How To Create JSON Array Using Jackson API – ObjectMapper – CreateArrayNode()
// To empty JSON Array parentArray.removeAll(); System.out.println("After removing all elements from array : "+ objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(parentArray)); package JacksonAPIUsage; import java.util.Arrays; import java.util.Iterator; import com.fasterxml.jackson.core.JsonProcessingException; 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; /* * [ { "firstname":"Jim", "lastname":"Brown", "totalprice":11
🌐
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)
NOTE: before Jackson 2.14 behavior was always that of non-expression usage; that is, exprOrProperty was always considered as a simple property name. public <T extends JsonNode> T withArray​(String exprOrProperty) Method that works in one of possible ways, depending on whether exprOrProperty is a valid JsonPointer expression or not (valid expression is either empty String "" or starts with leading slash / character).
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.

🌐
Fasterxml
fasterxml.github.io › jackson-databind › javadoc › 2.7 › com › fasterxml › jackson › databind › JsonNode.html
JsonNode (jackson-databind 2.7.0 API)
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 Iterator<Map.Entry<String,JsonNode>> fields()
🌐
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
🌐
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)
comparator - Object called to compare two scalar JsonNode instances, and return either 0 (are equals) or non-zero (not equal) ... Method that will produce (as of Jackson 2.10) valid JSON using default settings of databind, as String. If you want other kinds of JSON output (or output formatted using one of other Jackson-supported data formats) make sure to use ObjectMapper or ObjectWriter to serialize an instance, for example...
🌐
Fasterxml
fasterxml.github.io › jackson-databind › javadoc › 2.8 › com › fasterxml › jackson › databind › node › ObjectNode.html
ObjectNode (jackson-databind 2.8.0 API)
NOTE: Unlike all put(...) methods, return value is NOT this ObjectNode, but the newly created ObjectNode instance. ... Method for setting value of a field to specified numeric value. ... Alternative method that we need to avoid bumping into NPE issues with auto-unboxing. ... Method for setting value of a field to specified numeric value. The underlying JsonNode that will be added is constructed using JsonNodeFactory.numberNode(int), and may be "smaller" (like ShortNode) in cases where value fits within range of a smaller integral numeric value.
Top answer
1 of 4
52

This works, although intention is that it's factory that creates instances. But most commonly you just access all of it using ObjectMapper, like:

ObjectMapper mapper = new ObjectMapper();
ObjectNode dataTable = mapper.createObjectNode();
ArrayNode aa = dataTable.putArray("aaData");

The main reason for separate JsonNodeFactory is to allow you to create custom node types (usually sub-classes of standard instances); and then configure ObjectMapper to use different factory. For convenience, ArrayNode and ObjectNode do have reference to a factory instance, which is used with "putArray" and other methods that need to create new nodes.

2 of 4
7

If you do a lot of JsonNode building in code, you may be interesting in the following set of utilities. The benefit of using them is that they support a more natural chaining style that better shows the structure of the JSON under contruction.

Here is an example usage:

import static JsonNodeBuilders.array;
import static JsonNodeBuilders.object;

...

val request = object("x", "1").with("y", array(object("z", "2"))).end();

Which is equivalent to the following JSON:

{"x":"1", "y": [{"z": "2"}]}

Here are the classes:

import static lombok.AccessLevel.PRIVATE;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;

import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.val;

/**
 * Convenience {@link JsonNode} builder.
 */
@NoArgsConstructor(access = PRIVATE)
public final class JsonNodeBuilders {

  /**
   * Factory methods for an {@link ObjectNode} builder.
   */

  public static ObjectNodeBuilder object() {
    return object(JsonNodeFactory.instance);
  }

  public static ObjectNodeBuilder object(@NonNull String k1, boolean v1) {
    return object().with(k1, v1);
  }

  public static ObjectNodeBuilder object(@NonNull String k1, int v1) {
    return object().with(k1, v1);
  }

  public static ObjectNodeBuilder object(@NonNull String k1, float v1) {
    return object().with(k1, v1);
  }

  public static ObjectNodeBuilder object(@NonNull String k1, String v1) {
    return object().with(k1, v1);
  }

  public static ObjectNodeBuilder object(@NonNull String k1, String v1, @NonNull String k2, String v2) {
    return object(k1, v1).with(k2, v2);
  }

  public static ObjectNodeBuilder object(@NonNull String k1, String v1, @NonNull String k2, String v2,
      @NonNull String k3, String v3) {
    return object(k1, v1, k2, v2).with(k3, v3);
  }

  public static ObjectNodeBuilder object(@NonNull String k1, JsonNodeBuilder<?> builder) {
    return object().with(k1, builder);
  }

  public static ObjectNodeBuilder object(JsonNodeFactory factory) {
    return new ObjectNodeBuilder(factory);
  }

  /**
   * Factory methods for an {@link ArrayNode} builder.
   */

  public static ArrayNodeBuilder array() {
    return array(JsonNodeFactory.instance);
  }

  public static ArrayNodeBuilder array(@NonNull boolean... values) {
    return array().with(values);
  }

  public static ArrayNodeBuilder array(@NonNull int... values) {
    return array().with(values);
  }

  public static ArrayNodeBuilder array(@NonNull String... values) {
    return array().with(values);
  }

  public static ArrayNodeBuilder array(@NonNull JsonNodeBuilder<?>... builders) {
    return array().with(builders);
  }

  public static ArrayNodeBuilder array(JsonNodeFactory factory) {
    return new ArrayNodeBuilder(factory);
  }

  public interface JsonNodeBuilder<T extends JsonNode> {

    /**
     * Construct and return the {@link JsonNode} instance.
     */
    T end();

  }

  @RequiredArgsConstructor
  private static abstract class AbstractNodeBuilder<T extends JsonNode> implements JsonNodeBuilder<T> {

    /**
     * The source of values.
     */
    @NonNull
    protected final JsonNodeFactory factory;

    /**
     * The value under construction.
     */
    @NonNull
    protected final T node;

    /**
     * Returns a valid JSON string, so long as {@code POJONode}s not used.
     */
    @Override
    public String toString() {
      return node.toString();
    }

  }

  public final static class ObjectNodeBuilder extends AbstractNodeBuilder<ObjectNode> {

    private ObjectNodeBuilder(JsonNodeFactory factory) {
      super(factory, factory.objectNode());
    }

    public ObjectNodeBuilder withNull(@NonNull String field) {
      return with(field, factory.nullNode());
    }

    public ObjectNodeBuilder with(@NonNull String field, int value) {
      return with(field, factory.numberNode(value));
    }

    public ObjectNodeBuilder with(@NonNull String field, float value) {
      return with(field, factory.numberNode(value));
    }

    public ObjectNodeBuilder with(@NonNull String field, boolean value) {
      return with(field, factory.booleanNode(value));
    }

    public ObjectNodeBuilder with(@NonNull String field, String value) {
      return with(field, factory.textNode(value));
    }

    public ObjectNodeBuilder with(@NonNull String field, JsonNode value) {
      node.set(field, value);
      return this;
    }

    public ObjectNodeBuilder with(@NonNull String field, @NonNull JsonNodeBuilder<?> builder) {
      return with(field, builder.end());
    }

    public ObjectNodeBuilder withPOJO(@NonNull String field, @NonNull Object pojo) {
      return with(field, factory.pojoNode(pojo));
    }

    @Override
    public ObjectNode end() {
      return node;
    }

  }

  public final static class ArrayNodeBuilder extends AbstractNodeBuilder<ArrayNode> {

    private ArrayNodeBuilder(JsonNodeFactory factory) {
      super(factory, factory.arrayNode());
    }

    public ArrayNodeBuilder with(boolean value) {
      node.add(value);
      return this;
    }

    public ArrayNodeBuilder with(@NonNull boolean... values) {
      for (val value : values)
        with(value);
      return this;
    }

    public ArrayNodeBuilder with(int value) {
      node.add(value);
      return this;
    }

    public ArrayNodeBuilder with(@NonNull int... values) {
      for (val value : values)
        with(value);
      return this;
    }

    public ArrayNodeBuilder with(float value) {
      node.add(value);
      return this;
    }

    public ArrayNodeBuilder with(String value) {
      node.add(value);
      return this;
    }

    public ArrayNodeBuilder with(@NonNull String... values) {
      for (val value : values)
        with(value);
      return this;
    }

    public ArrayNodeBuilder with(@NonNull Iterable<String> values) {
      for (val value : values)
        with(value);
      return this;
    }

    public ArrayNodeBuilder with(JsonNode value) {
      node.add(value);
      return this;
    }

    public ArrayNodeBuilder with(@NonNull JsonNode... values) {
      for (val value : values)
        with(value);
      return this;
    }

    public ArrayNodeBuilder with(JsonNodeBuilder<?> value) {
      return with(value.end());
    }

    public ArrayNodeBuilder with(@NonNull JsonNodeBuilder<?>... builders) {
      for (val builder : builders)
        with(builder);
      return this;
    }

    @Override
    public ArrayNode end() {
      return node;
    }

  }

}

Note that the implementation uses Lombok, but you can easily desugar it to fill in the Java boilerplate.

🌐
Attacomsian
attacomsian.com › blog › jackson-create-json-object
How to create a JSON Object using Jackson
October 14, 2022 - A short tutorial to learn how to create a JSON object using Jackson API.
🌐
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 - import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; public class Main { public static void main(String[] args) { String jsonString = "{\"name\":\"John\",\"age\":30,\"address\":{\"street\":\"123 Main St\",\"city\":\"Anytown\"}}"; ObjectMapper objectMapper = new ObjectMapper(); try { // Parse JSON string into a JsonNode JsonNode rootNode = objectMapper.readTree(jsonString); // Accessing fields String name = rootNode.path("name").asText(); int age = rootNode.path("age").asInt(); String street = rootNode.path("address").path("street").asText(); String city = rootNode.path("address").path("city").asText(); System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("Street: " + street); System.out.println("City: " + city); } catch (Exception e) { e.printStackTrace(); } } }