MCPcopy
hub / github.com/FasterXML/jackson-databind

github.com/FasterXML/jackson-databind @jackson-databind-3.2.0 sqlite

repository ↗ · DeepWiki ↗ · release jackson-databind-3.2.0 ↗
24,843 symbols 91,297 edges 1,349 files 3,219 documented · 13%
README

Overview

This project contains the general-purpose data-binding functionality and tree-model for Jackson Data Processor. It builds on Streaming API (stream parser/generator) package, and uses Jackson Annotations for configuration. Project is licensed under Apache License 2.0.

While the original use case for Jackson was JSON data-binding, it can now be used to read content encoded in other data formats as well, as long as parser and generator implementations exist. Naming of classes uses word 'JSON' in many places even though there is no actual hard dependency to JSON format.

Status

Type Status
Build (CI) Build (github)
Artifact Maven Central
OSS Sponsorship Tidelift
Javadocs Javadoc
Code coverage (3.x) codecov.io
OpenSSF Score OpenSSF  Scorecard

Get it!

Maven

Functionality of this package is contained in Java package tools.jackson.databind (for Jackson 3.x), and can be used using following Maven dependency:

<properties>
  ...

  <jackson.version>3.0.0</jackson.version>
  ...
</properties>

<dependencies>
  ...
  <dependency>
    <groupId>tools.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>${jackson.version}</version>
  </dependency>
  ...
</dependencies>

Package also depends on jackson-core and jackson-annotations packages, but when using build tools like Maven or Gradle, dependencies are automatically included. You may, however, want to use jackson-bom to ensure compatible versions of dependencies. If not using build tool that can handle dependencies using project's pom.xml, you will need to download and include these 2 jars explicitly.

Non-Maven dependency resolution

For use cases that do not automatically resolve dependencies from Maven repositories, you can still download jars from Central Maven repository.

Databind jar is also a functional OSGi bundle, with proper import/export declarations, so it can be use on OSGi container as is.

Jackson 2.10 and above include module-info.class definitions so the jar is also a proper Java Module (JPMS).

Jackson 2.12 and above include additional Gradle 6 Module Metadata for version alignment with Gradle.


Compatibility

JDK

Jackson-databind package baseline JDK requirements are as follows:

  • Versions 2.x require JDK 8
  • Versions 3.x require JDK 17

Android

List is incomplete due to compatibility checker addition being done for Jackson 2.13.

  • 2.14 - 2.19: Android SDK 26+
  • 3.0: Android SDK 34+

for information on Android SDK versions to Android Release names see [https://en.wikipedia.org/wiki/Android_version_history]


Use It!

More comprehensive documentation can be found from Jackson-docs repository; as well as from Wiki of this project. But here are brief introductionary tutorials, in recommended order of reading.

1 minute tutorial: POJOs to JSON and back

The most common usage is to take piece of JSON, and construct a Plain Old Java Object ("POJO") out of it. So let's start there. With simple 2-property POJO like this:

// Note: can use getters/setters as well; here we just use public fields directly:
public class MyValue {
  public String name;
  public int age;
  // NOTE: if using getters/setters, can keep fields `protected` or `private`
}

we will need a tools.jackson.databind.ObjectMapper instance, used for all data-binding, so let's construct one:

// With default settings can use
ObjectMapper mapper = new ObjectMapper(); // create once, reuse

// But if configuration needed, use builder pattern:
ObjectMapper mapper = JsonMapper.builder()
    // configuration
    .build();

The default instance is fine for our use -- we will learn later on how to configure mapper instance if necessary. Usage is simple:

MyValue value = mapper.readValue(new File("data.json"), MyValue.class);
// or:
value = mapper.readValue(new URL("http://some.com/api/entry.json"), MyValue.class);
// or:
value = mapper.readValue("{\"name\":\"Bob\", \"age\":13}", MyValue.class);

And if we want to write JSON, we do the reverse:

mapper.writeValue(new File("result.json"), myResultObject);
// or:
byte[] jsonBytes = mapper.writeValueAsBytes(myResultObject);
// or:
String jsonString = mapper.writeValueAsString(myResultObject);

So far so good?

3 minute tutorial: Generic collections, Tree Model

Beyond dealing with simple Bean-style POJOs, you can also handle JDK Lists, Maps:

Map<String, Integer> scoreByName = mapper.readValue(jsonSource, Map.class);
List<String> names = mapper.readValue(jsonSource, List.class);

// and can obviously write out as well
mapper.writeValue(new File("names.json"), names);

as long as JSON structure matches, and types are simple. If you have POJO values, you need to indicate actual type (note: this is NOT needed for POJO properties with List etc types):

Map<String, ResultValue> results = mapper.readValue(jsonSource,
   new TypeReference<Map<String, ResultValue>>() { } );
// why extra work? Java Type Erasure will prevent type detection otherwise

(note: no extra effort needed for serialization, regardless of generic types)

But wait! There is more!

(enters Tree Model...)

Tree Model

While dealing with Maps, Lists and other "simple" Object types (Strings, Numbers, Booleans) can be simple, Object traversal can be cumbersome. This is where Jackson's Tree model can come in handy:

// can be read as generic JsonNode, if it can be Object or Array; or,
// if known to be Object, as ObjectNode, if array, ArrayNode etc:
JsonNode root = mapper.readTree("{ \"name\": \"Joe\", \"age\": 13 }");
String name = root.get("name").asText();
int age = root.get("age").asInt();

// can modify as well: this adds child Object as property 'other', set property 'type'
root.withObject("/other").put("type", "student");
String json = mapper.writeValueAsString(root); // prints below

/*
with above, we end up with something like as 'json' String:
{
  "name" : "Bob",
  "age" : 13,
  "other" : {
    "type" : "student"
  }
} 
*/

Tree Model can be more convenient than data-binding, especially in cases where structure is highly dynamic, or does not map nicely to Java classes.

Finally, feel free to mix and match, and even in the same json document (useful when only part of the document is known and modeled in your code)

// Some parts of this json are modeled in our code, some are not
JsonNode root = mapper.readTree(complexJson);
Person p = mapper.treeToValue(root.get("person"), Person.class); // known single pojo
Map<String, Object> dynamicmetadata = mapper.treeToValue(root.get("dynamicmetadata"), Map.class); // unknown smallish subfield, convert all to collections
int singledeep = root.get("deep").get("large").get("hiearchy").get("important").intValue(); // single value in very deep optional subfield, ignoring the rest
int singledeeppath = root.at("/deep/large/hiearchy/important").intValue(); // json path
int singledeeppathunique = root.findValue("important").intValue(); // by unique field name

// Send an aggregate json from heterogenous sources
ObjectNode root = mapper.createObjectNode();
root.putPOJO("person", new Person("Joe")); // simple pojo
root.putPOJO("friends", List.of(new Person("Jane"), new Person("Jack"))); // generics
Map<String, Object> dynamicmetadata = Map.of("Some", "Metadata");
root.putPOJO("dynamicmetadata", dynamicmetadata);  // collections
root.putPOJO("dynamicmetadata", mapper.valueToTree(dynamicmetadata)); // same thing
root.set("dynamicmetadata", mapper.valueToTree(dynamicmetadata)); // same thing
root.withObject("deep").withObject("large").withObject("hiearchy").put("important", 42); // create as you go
root.withObject("/deep/large/hiearchy").put("important", 42); // json path
mapper.writeValueAsString(root);

Supported for Jackson 2.16+ versions

// generics
List<Person> friends = mapper.treeToValue(root.get("friends"), new TypeReference<List<Person>>() { });
// create as you go but without trying json path
root.withObjectProperty("deep").withObjectProperty("large").withObjectProperty("hiearchy").put("important", 42);

5 minute tutorial: Streaming parser, generator

As convenient as data-binding (to/from POJOs) can be; and as flexible as Tree model can be, there is one more canonical processing model available: incremental (aka "streaming") model. It is the underlying processing model that data-binding and Tree Model both build upon, but it is also exposed to users who want ultimate performance and/or control over parsing or generation details.

For in-depth explanation, look at Jackson Core component. But let's look at a simple teaser to whet your appetite.

ObjectMapper mapper = ...;
// First: write simple JSON output
File jsonFile = new File("test.json");
// note: method added in Jackson 2.11 (earlier would need to use
// mapper.getFactory().createGenerator(...)
JsonGenerator g = mapper.createGenerator(jsonFile, JsonEncoding.UTF8);
// write JSON: { "message" : "Hello world!" }
g.writeStartObject();
g.writeStringField("message", "Hello world!");
g.writeEndObject();
g.close();

// Second: read file back
try (JsonParser p = mapper.createParser(jsonFile)) {
  JsonToken t = p.nextToken(); // Should be JsonToken.START_OBJECT
  t = p.nextToken(); // JsonToken.FIELD_NAME
  if ((t != JsonToken.FIELD_NAME) || !"message".equals(p.getCurrentName())) {
   // handle error
  }
  t = p.nextToken();
  if (t != JsonToken.VALUE_STRING) {
   // similarly
  }
  String msg = p.getText();
  System.out.printf("My message to you is: %s!\n", msg);
}

10 minute tutorial: configuration

There are two entry-level configuration mechanisms you are likely to use: Features and Annotations.

Commonly used Features

Here are examples of configuration features that you are most likely to need to know about.

Let's start with higher-level data-binding configuration. With Jackson 3.x, you need to use "Builder"-style construction (2.x also supported direct configuration but this was removed to make ObjectMapper instances immutable and fully thread-safe)

// SerializationFeature for changing how JSON is written

// to enable standard indentation ("pretty-printing"):

ObjcetMapper mapper = JsonMapper.builder()
    .enable(SerializationFeature.INDENT_OUTPUT)
    // to allow serialization of "empty" POJOs (no properties to serialize)
    // (without this setting, an exception is thrown in those cases)
    .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS)
    // to write java.util.Date, Calendar as number (timestamp):
    .disable(DateTimeFeature.WRITE_DATES_AS_TIMESTAMPS)

    // DeserializationFeature for changing how JSON is read as POJOs:

    // to prevent exception when encountering unknown property:
    .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
    // to allow coercion of JSON empty String ("") to null Object value:
    .enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT)

    .build();

In addition, you may need to change some of low-level JSON parsing, generation details. This happens by enabling disabling:

  • StreamReadFeature / StreamWriteFeature for generic (format-agnostic) settings
  • JsonReadFeature / JsonWriteFeature for JSON-specific settings
ObjcetMapper mapper = JsonMapper.builder()

    // StreamReadFeatures for configuring parsing settings:

    // to allow C/C++ style comments in JSON (non-standard, disabled by default)
    .configure(JsonReadFeature.ALLOW_JAVA_COMMENTS, true)
    // to allow (non-standard) unquoted field names in JSON:
    .configure(JsonReadFeature.ALLOW_UNQUOTED_PROPERTY_NAMES, true)
    // to allow use of apostrophes (single quotes), non standard
    .configure(JsonReadFeature.ALLOW_SINGLE_QUOTES, true)

    // JsonWriteFeature for configuring low-level JSON generation:

    // to force escaping of non-ASCII characters:
    .configure(JsonWriteFeature.ESCAPE_NON_ASCII, true)

    .build();

Full set of features are explained on Jackson Features page.

Annotations: changing property names

The simplest annotation-based approach is to use @JsonProperty annotation like so:

```java public class MyBean { private String _name;

// without annotat

Extension points exported contracts — how you extend this code

JacksonSerializable (Interface)
Interface that can be implemented by objects that know how to serialize themselves to JSON, using JsonGenerator [66 implementers]
src/main/java/tools/jackson/databind/JacksonSerializable.java
HashCodeMixIn (Interface)
(no doc) [64 implementers]
src/test/java/tools/jackson/databind/mixins/TestMixinDeserForClass.java
TypeIdResolver (Interface)
Interface that defines standard API for converting types to type identifiers and vice versa. Used by type resolvers ({@l [7 …
src/main/java/tools/jackson/databind/jsontype/TypeIdResolver.java
TestDataJAXBMixin (Interface)
(no doc) [87 implementers]
src/test/java/tools/jackson/databind/mixins/TestMixinSerWithViews.java
JsonFormatVisitable (Interface)
Interface tools.jackson.databind.ValueSerializer implements to allow for visiting type hierarchy. [60 implementers]
src/main/java/tools/jackson/databind/jsonFormatVisitors/JsonFormatVisitable.java
MyModelChildBase (Interface)
(no doc) [87 implementers]
src/test/java/tools/jackson/databind/mixins/MapperMixinsCopy1998Test.java
PropertyFilter (Interface)
Interface that defines API for filter objects use (as configured using {@link com.fasterxml.jackson.annotation.JsonFilte [9 …
src/main/java/tools/jackson/databind/ser/PropertyFilter.java
MapMarker (Interface)
(no doc) [8 implementers]
src/test/java/tools/jackson/databind/module/TestTypeModifiers.java

Core symbols most depended-on inside this repo

readValue
called by 3662
src/main/java/tools/jackson/databind/ObjectReader.java
writeValueAsString
called by 1746
src/main/java/tools/jackson/databind/ObjectWriter.java
build
called by 1570
src/test/java/tools/jackson/databind/jsontype/ext/ExternalTypeCustomResolver1288Test.java
get
called by 1563
src/main/java/tools/jackson/databind/BeanDescription.java
size
called by 925
src/main/java/tools/jackson/databind/util/LookupCache.java
readValue
called by 908
src/main/java/tools/jackson/databind/ObjectMapper.java
add
called by 789
src/test/java/tools/jackson/databind/ser/JsonValueSerializationTest.java
writeValueAsString
called by 698
src/main/java/tools/jackson/databind/ObjectMapper.java

Shape

Method 18,965
Class 5,408
Interface 235
Enum 229
Function 6

Languages

Java100%
Python1%

Modules by API surface

src/test/java/tools/jackson/databind/struct/UnwrappedBasicTest.java156 symbols
src/test/java/tools/jackson/databind/ser/JsonSerializeTest.java146 symbols
src/test/java/tools/jackson/databind/struct/ParentChildReferencesTest.java144 symbols
src/test/java/tools/jackson/databind/ser/GenericTypeSerializationTest.java137 symbols
src/test/java/tools/jackson/databind/struct/POJOAsArrayTest.java135 symbols
src/main/java/tools/jackson/databind/util/TokenBuffer.java133 symbols
src/test/java/tools/jackson/databind/ser/CustomSerializersTest.java132 symbols
src/test/java/tools/jackson/databind/deser/filter/DeserializationProblemHandlerTest.java124 symbols
src/main/java/tools/jackson/databind/JsonNode.java115 symbols
src/test/java/tools/jackson/databind/jsontype/ext/ExternalTypeIdTest.java114 symbols
src/main/java/tools/jackson/databind/DeserializationContext.java112 symbols
src/main/java/tools/jackson/databind/util/internal/PrivateMaxEntriesMap.java105 symbols

Dependencies from manifests, versioned

com.google.guava:guava-testlib32.0.1-jre · 1×
net.bytebuddy:byte-buddy
net.bytebuddy:byte-buddy-agent
org.assertj:assertj-core
org.junit.jupiter:junit-jupiter
org.junit.jupiter:junit-jupiter-api
org.junit.jupiter:junit-jupiter-params
org.mockito:mockito-core
tools.jackson.core:jackson-core

For agents

$ claude mcp add jackson-databind \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact