Bug: 199275786

Clone this repo:
  1. bb721f2 Fix errorprone warnings that should be errors am: a2570eedf1 am: 034e5f5a6f am: 056936fc0d by Cole Faust · 2 years, 2 months ago aml_hef_341811030 aml_rkp_341810000 android14-d2-release android14-d2-s1-release android14-d2-s2-release android14-d2-s3-release android14-d2-s4-release android14-d2-s5-release android14-dev android14-mainline-healthfitness-release android14-prebuilt-test android14-qpr1-automotiveos-release android14-qpr1-release android14-qpr1-s2-release android14-qpr2-release android14-qpr2-s1-release android14-qpr2-s2-release android14-qpr2-s3-release android14-qpr2-s4-release android14-qpr2-s5-release android14-qpr3-d1-release android14-qpr3-d1-s1-release android14-qpr3-d1-s2-release android14-qpr3-d1-s3-release android14-qpr3-release android14-qpr3-s10-release android14-qpr3-s11-release android14-qpr3-s12-release android14-qpr3-s13-release android14-qpr3-s14-release android14-qpr3-s15-release android14-qpr3-s2-release android14-qpr3-s3-release android14-qpr3-s4-release android14-qpr3-s5-release android14-qpr3-s6-release android14-qpr3-s7-release android14-qpr3-s8-release android14-qpr3-s9-release android15-automotiveos-dev android15-platform-release android15-prebuilt-test android15-qpr1-release android15-release android15-s1-release android15-security-release android15-tests-dev android15-tests-release main master aml_cfg_341510000 aml_cfg_351010000 aml_hef_341114030 aml_hef_341311010 aml_hef_341415040 aml_hef_341512030 aml_hef_341613000 aml_hef_341717050 aml_hef_341811030 aml_hef_350921160 aml_hef_351016140 aml_hef_351120040 aml_rkp_341012000 aml_rkp_341015010 aml_rkp_341114000 aml_rkp_341311000 aml_rkp_341510000 aml_rkp_341810000 aml_rkp_350910000 aml_rkp_351011000 aml_tz6_351010000 android-14.0.0_r16 android-14.0.0_r17 android-14.0.0_r18 android-14.0.0_r19 android-14.0.0_r20 android-14.0.0_r21 android-14.0.0_r22 android-14.0.0_r23 android-14.0.0_r24 android-14.0.0_r25 android-14.0.0_r26 android-14.0.0_r27 android-14.0.0_r29 android-14.0.0_r30 android-14.0.0_r31 android-14.0.0_r32 android-14.0.0_r33 android-14.0.0_r34 android-14.0.0_r35 android-14.0.0_r36 android-14.0.0_r37 android-14.0.0_r38 android-14.0.0_r39 android-14.0.0_r40 android-14.0.0_r41 android-14.0.0_r42 android-14.0.0_r43 android-14.0.0_r44 android-14.0.0_r45 android-14.0.0_r50 android-14.0.0_r51 android-14.0.0_r52 android-14.0.0_r53 android-14.0.0_r54 android-14.0.0_r55 android-14.0.0_r56 android-14.0.0_r57 android-14.0.0_r58 android-14.0.0_r59 android-14.0.0_r60 android-14.0.0_r61 android-14.0.0_r62 android-14.0.0_r63 android-14.0.0_r64 android-14.0.0_r65 android-14.0.0_r66 android-14.0.0_r67 android-14.0.0_r68 android-14.0.0_r69 android-14.0.0_r70 android-14.0.0_r71 android-14.0.0_r72 android-14.0.0_r73 android-14.0.0_r74 android-14.0.0_r75 android-15.0.0_r1 android-15.0.0_r2 android-15.0.0_r3 android-15.0.0_r4 android-15.0.0_r5 android-15.0.0_r6 android-15.0.0_r7 android-15.0.0_r8 android-15.0.0_r9 android-automotiveos-14.0.0_lts2 android-automotiveos-14.0.0_lts3 android-cts-15.0_r1 android-cts-15.0_r2 android-platform-15.0.0_r1 android-platform-15.0.0_r2 android-platform-15.0.0_r3 android-security-15.0.0_r1 android-security-15.0.0_r2 android-security-15.0.0_r3 android-vts-15.0_r1 android-vts-15.0_r2
  2. 056936f Fix errorprone warnings that should be errors am: a2570eedf1 am: 034e5f5a6f by Cole Faust · 2 years, 2 months ago android-u-beta-1-gpl
  3. 034e5f5 Fix errorprone warnings that should be errors am: a2570eedf1 by Cole Faust · 2 years, 2 months ago main-16k-with-phones
  4. a2570ee Fix errorprone warnings that should be errors by Cole Faust · 2 years, 2 months ago
  5. c8a9a05 Demote EqualsNull error to warning am: 814bd9b551 am: f787877193 am: 889b47941f am: cdeb77dbce am: 728a8a3d5a by Cole Faust · 2 years, 10 months ago

Overview

This project contains the general-purpose data-binding functionality and tree-model for Jackson Data Processor. It builds on core streaming 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 for 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.

Build Status Maven Central Javadoc Coverage Status


Get it!

Maven

Functionality of this package is contained in Java package com.fasterxml.jackson.databind, and can be used using following Maven dependency:

<properties>
  ...
  <!-- Use the latest version whenever possible. -->
  <jackson.version>2.10.0</jackson.version>
  ...
</properties>

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

Since package also depends on jackson-core and jackson-annotations packages, you will need to download these if not using Maven; and you may also want to add them as Maven dependency to ensure that compatible versions are used. If so, also add:

<dependencies>
  ...
  <dependency>
    <!-- Note: core-annotations version x.y.0 is generally compatible with
         (identical to) version x.y.1, x.y.2, etc. -->
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>${jackson.version}</version>
  </dependency>
  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>${jackson.version}</version>
  </dependency>
  ...
<dependencies>

but note that this is optional, and only necessary if there are conflicts between jackson core dependencies through transitive dependencies.

Non-Maven

For non-Maven use cases, you 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.


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 com.fasterxml.jackson.databind.ObjectMapper instance, used for all data-binding, so let's construct one:

ObjectMapper mapper = new ObjectMapper(); // create once, reuse

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!

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:
ObjectNode root = mapper.readTree("stuff.json");
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.with("other").put("type", "student");
String json = mapper.writeValueAsString(root);

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

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.

JsonFactory f = mapper.getFactory(); // may alternatively construct directly too

// First: write simple JSON output
File jsonFile = new JsonFile("test.json");
JsonGenerator g = f.createGenerator(jsonFile);
// write JSON: { "message" : "Hello world!" }
g.writeStartObject();
g.writeStringField("message", "Hello world!");
g.writeEndObject();
g.close();

// Second: read file back
JsonParser p = f.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);
p.close();

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.

// SerializationFeature for changing how JSON is written

// to enable standard indentation ("pretty-printing"):
mapper.enable(SerializationFeature.INDENT_OUTPUT);
// to allow serialization of "empty" POJOs (no properties to serialize)
// (without this setting, an exception is thrown in those cases)
mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
// to write java.util.Date, Calendar as number (timestamp):
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

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

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

In addition, you may need to change some of low-level JSON parsing, generation details:

// JsonParser.Feature for configuring parsing settings:

// to allow C/C++ style comments in JSON (non-standard, disabled by default)
// (note: with Jackson 2.5, there is also `mapper.enable(feature)` / `mapper.disable(feature)`)
mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
// to allow (non-standard) unquoted field names in JSON:
mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
// to allow use of apostrophes (single quotes), non standard
mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);

// JsonGenerator.Feature for configuring low-level JSON generation:

// to force escaping of non-ASCII characters:
mapper.configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true);

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:

public class MyBean {
   private String _name;

   // without annotation, we'd get "theName", but we want "name":
   @JsonProperty("name")
   public String getTheName() { return _name; }

   // note: it is enough to add annotation on just getter OR setter;
   // so we can omit it here
   public void setTheName(String n) { _name = n; }
}

There are other mechanisms to use for systematic naming changes: see Custom Naming Convention for details.

Note, too, that you can use Mix-in Annotations to associate all annotations.

Annotations: Ignoring properties

There are two main annotations that can be used to to ignore properties: @JsonIgnore for individual properties; and @JsonIgnoreProperties for per-class definition

// means that if we see "foo" or "bar" in JSON, they will be quietly skipped
// regardless of whether POJO has such properties
@JsonIgnoreProperties({ "foo", "bar" })
public class MyBean
{
   // will not be written as JSON; nor assigned from JSON:
   @JsonIgnore
   public String internal;

   // no annotation, public field is read/written normally
   public String external;

   @JsonIgnore
   public void setCode(int c) { _code = c; }

   // note: will also be ignored because setter has annotation!
   public int getCode() { return _code; }
}

As with renaming, note that annotations are “shared” between matching fields, getters and setters: if only one has @JsonIgnore, it affects others. But it is also possible to use “split” annotations, to for example:

public class ReadButDontWriteProps {
   private String _name;
   @JsonProperty public void setName(String n) { _name = n; }
   @JsonIgnore public String getName() { return _name; }
}

in this case, no “name” property would be written out (since ‘getter’ is ignored); but if “name” property was found from JSON, it would be assigned to POJO property!

For a more complete explanation of all possible ways of ignoring properties when writing out JSON, check “Filtering properties” article.

Annotations: using custom constructor

Unlike many other data-binding packages, Jackson does not require you to define “default constructor” (constructor that does not take arguments). While it will use one if nothing else is available, you can easily define that an argument-taking constructor is used:

public class CtorBean
{
  public final String name;
  public final int age;

  @JsonCreator // constructor can be public, private, whatever
  private CtorBean(@JsonProperty("name") String name,
    @JsonProperty("age") int age)
  {
      this.name = name;
      this.age = age;
  }
}

Constructors are especially useful in supporting use of Immutable objects.

Alternatively, you can also define “factory methods”:

public class FactoryBean
{
    // fields etc omitted for brewity

    @JsonCreator
    public static FactoryBean create(@JsonProperty("name") String name) {
      // construct and return an instance
    }
}

Note that use of a “creator method” (@JsonCreator with @JsonProperty annotated arguments) does not preclude use of setters: you can mix and match properties from constructor/factory method with ones that are set via setters or directly using fields.

Tutorial: fancier stuff, conversions

One useful (but not very widely known) feature of Jackson is its ability to do arbitrary POJO-to-POJO conversions. Conceptually you can think of conversions as sequence of 2 steps: first, writing a POJO as JSON, and second, binding that JSON into another kind of POJO. Implementation just skips actual generation of JSON, and uses more efficient intermediate representation.

Conversions work between any compatible types, and invocation is as simple as:

ResultType result = mapper.convertValue(sourceObject, ResultType.class);

and as long as source and result types are compatible -- that is, if to-JSON, from-JSON sequence would succeed -- things will “just work”. But here are couple of potentially useful use cases:

// Convert from List<Integer> to int[]
List<Integer> sourceList = ...;
int[] ints = mapper.convertValue(sourceList, int[].class);
// Convert a POJO into Map!
Map<String,Object> propertyMap = mapper.convertValue(pojoValue, Map.class);
// ... and back
PojoType pojo = mapper.convertValue(propertyMap, PojoType.class);
// decode Base64! (default byte[] representation is base64-encoded String)
String base64 = "TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz";
byte[] binary = mapper.convertValue(base64, byte[].class);

Basically, Jackson can work as a replacement for many Apache Commons components, for tasks like base64 encoding/decoding, and handling of “dyna beans” (Maps to/from POJOs).

Contribute!

We would love to get your contribution, whether it's in form of bug reports, Requests for Enhancement (RFE), documentation, or code patches. The primary mechanism for all of above is GitHub Issues system.

Basic rules for Code Contributions

There is really just one main rule, which is that to accept any code contribution, we need to get a filled Contributor License Agreement (CLA) from the author. One CLA is enough for any number of contributions, but we need one. Or, rather, companies that use our code want it. It keeps their lawyers less unhappy about Open Source usage.

Limitation on Dependencies by Core Components

One additional limitation exists for so-called core components (streaming api, jackson-annotations and jackson-databind): no additional dependendies are allowed beyond:

  • Core components may rely on any methods included in the supported JDK
    • Minimum JDK version was 1.5 until (and including) version 2.3
    • Minimum JDK version was 1.6 for Jackson 2.4 - 2.7 (inclusive) for all core components
      • Minimum is still 1.6 for jackson-annotations and jackson-core, for all remaining Jackson 2.x versions
    • Minimum JDK version is 1.7 for Jackson 2.7 - 2.10 of jackson-databind and most non-core components
  • Jackson-databind (this package) depends on the other two (annotations, streaming).

This means that anything that has to rely on additional APIs or libraries needs to be built as an extension, usually a Jackson module.

Branches

master branch is for developing the next major Jackson version -- 3.0 -- but there are active maintenance branches in which much of development happens:

  • 2.10 is the current stable minor 2.x version
  • 2.9 is for selected backported fixes

Older branches are usually not maintained after being declared as closed on Jackson Releases page, but exist just in case a rare emergency patch is needed. All released versions have matching git tags (jackson-dataformats-binary-2.9.10).


Differences from Jackson 1.x

Project contains versions 2.0 and above: source code for earlier (1.x) versions was available from Codehaus SVN repository, but due to Codehaus closure is currently (July 2015) not officially available. We may try to create Jackson1x repository at Github in future (if you care about this, ping Jackson team via mailing lists, or file an issue for this project).

Main differences compared to 1.0 “mapper” jar are:

  • Maven build instead of Ant
  • Java package is now com.fasterxml.jackson.databind (instead of org.codehaus.jackson.map)

Further reading

Related: