• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..--

.github/23-Nov-2023-86

android/src/com/fasterxml/jackson/databind/cfg/23-Nov-2023-2312

attic/23-Nov-2023-638428

docs/javadoc/23-Nov-2023-6,809,0426,048,292

release-notes/23-Nov-2023-3,3572,871

src/23-Nov-2023-250,980176,776

.gitattributesD23-Nov-2023217 86

.gitignoreD23-Nov-2023172 2520

.travis.ymlD23-Nov-20231.2 KiB3420

Android.bpD23-Nov-20231.2 KiB4541

LICENSED23-Nov-2023321 96

METADATAD23-Nov-2023621 2119

MODULE_LICENSE_APACHE2D23-Nov-20230

OWNERSD23-Nov-202376 43

README.mdD23-Nov-202318.2 KiB453332

SECURITY.mdD23-Nov-20231.2 KiB2316

create-test-report.shD23-Nov-202340 41

pom.xmlD23-Nov-20239.4 KiB273214

profile.shD23-Nov-2023141 73

run.shD23-Nov-202383 51

README.md

1# Overview
2
3This project contains the general-purpose data-binding functionality
4and tree-model for [Jackson Data Processor](http://wiki.fasterxml.com/JacksonHome).
5It builds on [core streaming parser/generator](../../../jackson-core) package,
6and uses [Jackson Annotations](../../../jackson-annotations) for configuration.
7Project is licensed under [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0).
8
9While 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.
10Naming of classes uses word 'JSON' in many places even though there is no actual hard dependency to JSON format.
11
12[![Build Status](https://travis-ci.org/FasterXML/jackson-databind.svg?branch=master)](https://travis-ci.org/FasterXML/jackson-databind) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.fasterxml.jackson.core/jackson-databind/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.fasterxml.jackson.core/jackson-databind)
13[![Javadoc](https://javadoc-emblem.rhcloud.com/doc/com.fasterxml.jackson.core/jackson-databind/badge.svg)](http://www.javadoc.io/doc/com.fasterxml.jackson.core/jackson-databind)
14[![Coverage Status](https://coveralls.io/repos/github/FasterXML/jackson-databind/badge.svg?branch=master)](https://coveralls.io/github/FasterXML/jackson-databind?branch=master)
15
16-----
17
18# Get it!
19
20## Maven
21
22Functionality of this package is contained in Java package `com.fasterxml.jackson.databind`, and can be used using following Maven dependency:
23
24```xml
25<properties>
26  ...
27  <!-- Use the latest version whenever possible. -->
28  <jackson.version>2.10.0</jackson.version>
29  ...
30</properties>
31
32<dependencies>
33  ...
34  <dependency>
35    <groupId>com.fasterxml.jackson.core</groupId>
36    <artifactId>jackson-databind</artifactId>
37    <version>${jackson.version}</version>
38  </dependency>
39  ...
40</dependencies>
41```
42
43Since 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.
44If so, also add:
45
46```xml
47<dependencies>
48  ...
49  <dependency>
50    <!-- Note: core-annotations version x.y.0 is generally compatible with
51         (identical to) version x.y.1, x.y.2, etc. -->
52    <groupId>com.fasterxml.jackson.core</groupId>
53    <artifactId>jackson-annotations</artifactId>
54    <version>${jackson.version}</version>
55  </dependency>
56  <dependency>
57    <groupId>com.fasterxml.jackson.core</groupId>
58    <artifactId>jackson-core</artifactId>
59    <version>${jackson.version}</version>
60  </dependency>
61  ...
62<dependencies>
63```
64
65but note that this is optional, and only necessary if there are conflicts between jackson core dependencies through transitive dependencies.
66
67## Non-Maven
68
69For non-Maven use cases, you download jars from [Central Maven repository](http://repo1.maven.org/maven2/com/fasterxml/jackson/core/jackson-databind/).
70
71Databind jar is also a functional OSGi bundle, with proper import/export declarations, so it can be use on OSGi container as is.
72
73-----
74
75# Use It!
76
77More comprehensive documentation can be found from [Jackson-docs](../../../jackson-docs) repository; as well as from [Wiki](../../wiki) of this project.
78But here are brief introductionary tutorials, in recommended order of reading.
79
80## 1 minute tutorial: POJOs to JSON and back
81
82The 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:
83
84```java
85// Note: can use getters/setters as well; here we just use public fields directly:
86public class MyValue {
87  public String name;
88  public int age;
89  // NOTE: if using getters/setters, can keep fields `protected` or `private`
90}
91```
92
93we will need a `com.fasterxml.jackson.databind.ObjectMapper` instance, used for all data-binding, so let's construct one:
94
95```java
96ObjectMapper mapper = new ObjectMapper(); // create once, reuse
97```
98
99The default instance is fine for our use -- we will learn later on how to configure mapper instance if necessary. Usage is simple:
100
101```java
102MyValue value = mapper.readValue(new File("data.json"), MyValue.class);
103// or:
104value = mapper.readValue(new URL("http://some.com/api/entry.json"), MyValue.class);
105// or:
106value = mapper.readValue("{\"name\":\"Bob\", \"age\":13}", MyValue.class);
107```
108
109And if we want to write JSON, we do the reverse:
110
111```java
112mapper.writeValue(new File("result.json"), myResultObject);
113// or:
114byte[] jsonBytes = mapper.writeValueAsBytes(myResultObject);
115// or:
116String jsonString = mapper.writeValueAsString(myResultObject);
117```
118
119So far so good?
120
121## 3 minute tutorial: Generic collections, Tree Model
122
123Beyond dealing with simple Bean-style POJOs, you can also handle JDK `List`s, `Map`s:
124
125```java
126Map<String, Integer> scoreByName = mapper.readValue(jsonSource, Map.class);
127List<String> names = mapper.readValue(jsonSource, List.class);
128
129// and can obviously write out as well
130mapper.writeValue(new File("names.json"), names);
131```
132
133as long as JSON structure matches, and types are simple.
134If you have POJO values, you need to indicate actual type (note: this is NOT needed for POJO properties with `List` etc types):
135
136```java
137Map<String, ResultValue> results = mapper.readValue(jsonSource,
138   new TypeReference<Map<String, ResultValue>>() { } );
139// why extra work? Java Type Erasure will prevent type detection otherwise
140```
141
142(note: no extra effort needed for serialization, regardless of generic types)
143
144But wait! There is more!
145
146While dealing with `Map`s, `List`s and other "simple" Object types (Strings, Numbers, Booleans) can be simple, Object traversal can be cumbersome.
147This is where Jackson's [Tree model](https://github.com/FasterXML/jackson-databind/wiki/JacksonTreeModel) can come in handy:
148
149```java
150// can be read as generic JsonNode, if it can be Object or Array; or,
151// if known to be Object, as ObjectNode, if array, ArrayNode etc:
152ObjectNode root = mapper.readTree("stuff.json");
153String name = root.get("name").asText();
154int age = root.get("age").asInt();
155
156// can modify as well: this adds child Object as property 'other', set property 'type'
157root.with("other").put("type", "student");
158String json = mapper.writeValueAsString(root);
159
160// with above, we end up with something like as 'json' String:
161// {
162//   "name" : "Bob", "age" : 13,
163//   "other" : {
164//      "type" : "student"
165//   }
166// }
167```
168
169Tree Model can be more convenient than data-binding, especially in cases where structure is highly dynamic, or does not map nicely to Java classes.
170
171## 5 minute tutorial: Streaming parser, generator
172
173As 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.
174It 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.
175
176For in-depth explanation, look at [Jackson Core component](https://github.com/FasterXML/jackson-core).
177But let's look at a simple teaser to whet your appetite.
178
179```java
180JsonFactory f = mapper.getFactory(); // may alternatively construct directly too
181
182// First: write simple JSON output
183File jsonFile = new JsonFile("test.json");
184JsonGenerator g = f.createGenerator(jsonFile);
185// write JSON: { "message" : "Hello world!" }
186g.writeStartObject();
187g.writeStringField("message", "Hello world!");
188g.writeEndObject();
189g.close();
190
191// Second: read file back
192JsonParser p = f.createParser(jsonFile);
193
194JsonToken t = p.nextToken(); // Should be JsonToken.START_OBJECT
195t = p.nextToken(); // JsonToken.FIELD_NAME
196if ((t != JsonToken.FIELD_NAME) || !"message".equals(p.getCurrentName())) {
197   // handle error
198}
199t = p.nextToken();
200if (t != JsonToken.VALUE_STRING) {
201   // similarly
202}
203String msg = p.getText();
204System.out.printf("My message to you is: %s!\n", msg);
205p.close();
206
207```
208
209## 10 minute tutorial: configuration
210
211There are two entry-level configuration mechanisms you are likely to use:
212[Features](https://github.com/FasterXML/jackson-databind/wiki/JacksonFeatures) and [Annotations](https://github.com/FasterXML/jackson-annotations).
213
214### Commonly used Features
215
216Here are examples of configuration features that you are most likely to need to know about.
217
218Let's start with higher-level data-binding configuration.
219
220```java
221// SerializationFeature for changing how JSON is written
222
223// to enable standard indentation ("pretty-printing"):
224mapper.enable(SerializationFeature.INDENT_OUTPUT);
225// to allow serialization of "empty" POJOs (no properties to serialize)
226// (without this setting, an exception is thrown in those cases)
227mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
228// to write java.util.Date, Calendar as number (timestamp):
229mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
230
231// DeserializationFeature for changing how JSON is read as POJOs:
232
233// to prevent exception when encountering unknown property:
234mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
235// to allow coercion of JSON empty String ("") to null Object value:
236mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
237```
238
239In addition, you may need to change some of low-level JSON parsing, generation details:
240
241```java
242// JsonParser.Feature for configuring parsing settings:
243
244// to allow C/C++ style comments in JSON (non-standard, disabled by default)
245// (note: with Jackson 2.5, there is also `mapper.enable(feature)` / `mapper.disable(feature)`)
246mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
247// to allow (non-standard) unquoted field names in JSON:
248mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
249// to allow use of apostrophes (single quotes), non standard
250mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
251
252// JsonGenerator.Feature for configuring low-level JSON generation:
253
254// to force escaping of non-ASCII characters:
255mapper.configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true);
256```
257
258Full set of features are explained on [Jackson Features](https://github.com/FasterXML/jackson-databind/wiki/JacksonFeatures) page.
259
260### Annotations: changing property names
261
262The simplest annotation-based approach is to use `@JsonProperty` annotation like so:
263
264```java
265public class MyBean {
266   private String _name;
267
268   // without annotation, we'd get "theName", but we want "name":
269   @JsonProperty("name")
270   public String getTheName() { return _name; }
271
272   // note: it is enough to add annotation on just getter OR setter;
273   // so we can omit it here
274   public void setTheName(String n) { _name = n; }
275}
276```
277
278There are other mechanisms to use for systematic naming changes: see [Custom Naming Convention](https://github.com/FasterXML/jackson-databind/wiki/JacksonCustomNamingConvention) for details.
279
280Note, too, that you can use [Mix-in Annotations](https://github.com/FasterXML/jackson-databind/wiki/JacksonMixinAnnotations) to associate all annotations.
281
282### Annotations: Ignoring properties
283
284There are two main annotations that can be used to to ignore properties: `@JsonIgnore` for individual properties; and `@JsonIgnoreProperties` for per-class definition
285
286```java
287// means that if we see "foo" or "bar" in JSON, they will be quietly skipped
288// regardless of whether POJO has such properties
289@JsonIgnoreProperties({ "foo", "bar" })
290public class MyBean
291{
292   // will not be written as JSON; nor assigned from JSON:
293   @JsonIgnore
294   public String internal;
295
296   // no annotation, public field is read/written normally
297   public String external;
298
299   @JsonIgnore
300   public void setCode(int c) { _code = c; }
301
302   // note: will also be ignored because setter has annotation!
303   public int getCode() { return _code; }
304}
305```
306
307As with renaming, note that annotations are "shared" between matching fields, getters and setters: if only one has `@JsonIgnore`, it affects others.
308But it is also possible to use "split" annotations, to for example:
309
310```java
311public class ReadButDontWriteProps {
312   private String _name;
313   @JsonProperty public void setName(String n) { _name = n; }
314   @JsonIgnore public String getName() { return _name; }
315}
316```
317
318in 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!
319
320For a more complete explanation of all possible ways of ignoring properties when writing out JSON, check ["Filtering properties"](http://www.cowtowncoder.com/blog/archives/2011/02/entry_443.html) article.
321
322### Annotations: using custom constructor
323
324Unlike many other data-binding packages, Jackson does not require you to define "default constructor" (constructor that does not take arguments).
325While it will use one if nothing else is available, you can easily define that an argument-taking constructor is used:
326
327```java
328public class CtorBean
329{
330  public final String name;
331  public final int age;
332
333  @JsonCreator // constructor can be public, private, whatever
334  private CtorBean(@JsonProperty("name") String name,
335    @JsonProperty("age") int age)
336  {
337      this.name = name;
338      this.age = age;
339  }
340}
341```
342
343Constructors are especially useful in supporting use of
344[Immutable objects](http://www.cowtowncoder.com/blog/archives/2010/08/entry_409.html).
345
346Alternatively, you can also define "factory methods":
347
348```java
349public class FactoryBean
350{
351    // fields etc omitted for brewity
352
353    @JsonCreator
354    public static FactoryBean create(@JsonProperty("name") String name) {
355      // construct and return an instance
356    }
357}
358```
359
360Note that use of a "creator method" (`@JsonCreator` with `@JsonProperty` annotated arguments) does not preclude use of setters: you
361can mix and match properties from constructor/factory method with ones that
362are set via setters or directly using fields.
363
364## Tutorial: fancier stuff, conversions
365
366One useful (but not very widely known) feature of Jackson is its ability
367to 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.
368
369Conversions work between any compatible types, and invocation is as simple as:
370
371```java
372ResultType result = mapper.convertValue(sourceObject, ResultType.class);
373```
374
375and as long as source and result types are compatible -- that is, if to-JSON, from-JSON sequence would succeed -- things will "just work".
376But here are couple of potentially useful use cases:
377
378```java
379// Convert from List<Integer> to int[]
380List<Integer> sourceList = ...;
381int[] ints = mapper.convertValue(sourceList, int[].class);
382// Convert a POJO into Map!
383Map<String,Object> propertyMap = mapper.convertValue(pojoValue, Map.class);
384// ... and back
385PojoType pojo = mapper.convertValue(propertyMap, PojoType.class);
386// decode Base64! (default byte[] representation is base64-encoded String)
387String base64 = "TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz";
388byte[] binary = mapper.convertValue(base64, byte[].class);
389```
390
391Basically, 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).
392
393# Contribute!
394
395We would love to get your contribution, whether it's in form of bug reports, Requests for Enhancement (RFE), documentation, or code patches.
396The primary mechanism for all of above is [GitHub Issues system](https://github.com/FasterXML/jackson-databind/issues).
397
398## Basic rules for Code Contributions
399
400There 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.
401
402## Limitation on Dependencies by Core Components
403
404One additional limitation exists for so-called core components (streaming api, jackson-annotations and jackson-databind): no additional dependendies are allowed beyond:
405
406* Core components may rely on any methods included in the supported JDK
407    * Minimum JDK version was 1.5 until (and including) version 2.3
408    * Minimum JDK version was 1.6 for Jackson 2.4 - 2.7 (inclusive) for all core components
409        * Minimum is still 1.6 for `jackson-annotations` and `jackson-core`, for all remaining Jackson 2.x versions
410    * Minimum JDK version is 1.7 for Jackson 2.7 - 2.10 of `jackson-databind` and most non-core components
411* Jackson-databind (this package) depends on the other two (annotations, streaming).
412
413This means that anything that has to rely on additional APIs or libraries needs to be built as an extension,
414usually a Jackson module.
415
416
417## Branches
418
419`master` branch is for developing the next major Jackson version -- 3.0 -- but there
420are active maintenance branches in which much of development happens:
421
422* `2.10` is the current stable minor 2.x version
423* `2.9` is for selected backported fixes
424
425Older branches are usually not maintained after being declared as closed
426on [Jackson Releases](https://github.com/FasterXML/jackson/wiki/Jackson-Releases) page,
427but exist just in case a rare emergency patch is needed.
428All released versions have matching git tags (`jackson-dataformats-binary-2.9.10`).
429
430-----
431
432# Differences from Jackson 1.x
433
434Project contains versions 2.0 and above: source code for earlier (1.x) versions was available from [Codehaus](http://jackson.codehaus.org) SVN repository, but due to Codehaus closure is currently (July 2015) not officially available.
435We 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).
436
437Main differences compared to 1.0 "mapper" jar are:
438
439* Maven build instead of Ant
440* Java package is now `com.fasterxml.jackson.databind` (instead of `org.codehaus.jackson.map`)
441
442-----
443
444# Further reading
445
446* [Overall Jackson Docs](../../../jackson-docs)
447* [Project wiki page](https://github.com/FasterXML/jackson-databind/wiki)
448
449Related:
450
451* [Core annotations](https://github.com/FasterXML/jackson-annotations) package defines annotations commonly used for configuring databinding details
452* [Core parser/generator](https://github.com/FasterXML/jackson-core) package defines low-level incremental/streaming parsers, generators
453