• Stars
    star
    570
  • Rank 78,245 (Top 2 %)
  • Language
    Java
  • License
    Apache License 2.0
  • Created almost 14 years ago
  • Updated 30 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Extension for Jackson JSON processor that adds support for serializing POJOs as XML (and deserializing from XML) as an alternative to JSON

Overview

This projects contains Jackson extension component for reading and writing XML encoded data.

Further, the goal is to emulate how JAXB data-binding works with "Code-first" approach (no support is added for "Schema-first" approach). Support for JAXB annotations is provided by JAXB annotation module; this module provides low-level abstractions (JsonParser, JsonGenerator, JsonFactory) as well as small number of higher level overrides needed to make data-binding work.

It is worth noting, however, that the goal is NOT to be full JAXB clone; or to be a general purpose XML toolkit.

Specifically:

  • While XML serialization should ideally be similar to JAXB output, deviations are not automatically considered flaws (there are reasons for some differences)
  • What should be guaranteed is that any XML written using this module must be readable using module as well ("read what I wrote"): that is, we do aim for full round-trip support
  • From above: there are XML constructs that module will not be able to handle; including some cases JAXB (and other Java XML libraries) supports
  • This module also support constructs and use cases JAXB does not handle: specifically, rich type and object id support of Jackson are supported.

Status

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

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.16 is for developing the next minor 2.x version
  • 2.15 is for backported fixes to include in 2.15.x patch versions
  • 2.14 is for backported fixes to include in 2.14.x patch versions
  • 2.13 is for backported fixes to include in 2.13.x patch versions

Older branches are usually not changed but are available for historic reasons. All released versions have matching git tags (jackson-dataformats-text-2.9.4).

License

All modules are licensed under Apache License 2.0.

Maven dependency

To use Jackson 2.x compatible version of this extension on Maven-based projects, use following dependency:

Maven:

<dependency>
  <groupId>com.fasterxml.jackson.dataformat</groupId>
  <artifactId>jackson-dataformat-xml</artifactId>
  <version>2.15.0</version>
</dependency>

Gradle:

dependencies {
    implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.15.0'
}

(or whatever version is most up-to-date at the moment)

Also: you usually also want to make sure that XML library in use is Woodstox since it is not only faster than Stax implementation JDK provides, but also works better and avoids some known issues like adding unnecessary namespace prefixes. You can do this by adding this in your pom.xml:

Maven:

<dependency>
  <groupId>com.fasterxml.woodstox</groupId>
  <artifactId>woodstox-core</artifactId>
  <version>6.5.0</version>
</dependency>

Gradle:

dependencies {
    implementation 'com.fasterxml.woodstox:woodstox-core:6.5.0'
}

Usage

Although module implements low-level (JsonFactory / JsonParser / JsonGenerator) abstractions, most usage is through data-binding level. This because a small number of work-arounds have been added at data-binding level, to work around XML peculiarities: that is, stream of JsonTokens that parser produces has idiosyncracies that need special handling.

Usually you either create XmlMapper simply by:

XmlMapper mapper = new XmlMapper();

but in case you need to configure settings, you will want to use Builder (added in Jackson 2.10) style construction:

XmlMapper mapper = XmlMapper.builder()
   .defaultUseWrapper(false)
   // enable/disable Features, change AnnotationIntrospector
   .build();

Alternatively, sometimes you may want/need to configure low-level XML processing details controlled by underlying Stax library (Woodstox, Aalto or JDK-default Oracle implementation). If so, you will need to construct XmlMapper with properly configured underlying factories. This usually looks something like:

XMLInputFactory ifactory = new WstxInputFactory(); // Woodstox XMLInputFactory impl
ifactory.setProperty(WstxInputProperties.P_MAX_ATTRIBUTE_SIZE, 32000);
// configure
XMLOutputFactory ofactory = new WstxOutputFactory(); // Woodstox XMLOutputfactory impl
ofactory.setProperty(WstxOutputProperties.P_OUTPUT_CDATA_AS_TEXT, true);
XmlFactory xf = XmlFactory.builder()
    .xmlInputFactory(ifactory) // note: in 2.12 and before "inputFactory()"
    .xmlOutputFactory(ofactory) // note: in 2.12 and before "outputFactory()"
    .builder();
XmlMapper mapper = new XmlMapper(xf); // there are other overloads too

For configurable properties, you may want to check out Configuring Woodstox XML parser

As the well as the Woodstox properties specified above, you can also call WstxInputFactory#getConfig() and modify the ReaderConfig. One useful setting is the maxElementDepth.

Android quirks

Usage of this library on Android is currently not supported. This is due to the fact that the Stax API is unavailable on the Android platform, and attempts to declare an explicit dependency on the Stax API library will result in errors at build time (since the inclusion of the javax.* namespace in apps is restricted). For more on the issues, see:

Note that as per articles linked to it MAY be possible to use the module on Android, but it unfortunately requires various work-arounds and development team can not do much to alleviate these issues. Suggestions for improvements would be welcome; discussions on Jackson users list encouraged.

Serializing POJOs as XML

Serialization is done very similar to JSON serialization: all that needs to change is ObjectMapper instance to use:

// Important: create XmlMapper; it will use proper factories, workarounds
ObjectMapper xmlMapper = new XmlMapper();
String xml = xmlMapper.writeValueAsString(new Simple());
// or
xmlMapper.writeValue(new File("/tmp/stuff.xml"), new Simple());

and with POJO like:

public class Simple {
    public int x = 1;
    public int y = 2;
}

you would get something like:

<Simple>
  <x>1</x>
  <y>2</y>
</Simple>

(except that by default output is not indented: you can enabled indentation using standard Jackson mechanisms)

Deserializing POJOs from XML

Similar to serialization, deserialization is not very different from JSON deserialization:

ObjectMapper xmlMapper = new XmlMapper();
Simple value = xmlMapper.readValue("<Simple><x>1</x><y>2</y></Simple>", Simple.class);

Incremental/partial reading/writing (2.4+)

It is also possible to do incremental writes. This is done by creating Stax XMLInputFactory separately (similar to how with JSON you would create JsonGenerator), and then:

// First create Stax components we need
XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newFactory();
StringWriter out = new StringWriter();
XMLStreamWriter sw = xmlOutputFactory.createXMLStreamWriter(out);

// then Jackson components
XmlMapper mapper = new XmlMapper(xmlInputFactory);

sw.writeStartDocument();
sw.writeStartElement("root");

// Write whatever content POJOs...
SomePojo value1 = ...;
OtherPojo value2 = ...;
mapper.writeValue(sw, value1);
mapper.writeValue(sw, value2);
// and/or regular Stax output
sw.writeComment("Some insightful commentary here");
sw.writeEndElement();
sw.writeEndDocument();

Similarly it is possible to read content, sub-tree by sub-tree; assuming similar XML content we would use

XMLInputFactory f = XMLInputFactory.newFactory();
File inputFile = ...;
XMLStreamReader sr = f.createXMLStreamReader(new FileInputStream(inputFile));

XmlMapper mapper = new XmlMapper();
sr.next(); // to point to <root>
sr.next(); // to point to root-element under root
SomePojo value1 = mapper.readValue(sr, SomePojo.class);
// sr now points to matching END_ELEMENT, so move forward
sr.next(); // should verify it's either closing root or new start, left as exercise
OtherPojo value = mapper.readValue(sr, OtherPojo.class);
// and more, as needed, then
sr.close();

Additional annotations

In addition to standard Jackson annotations and optional JAXB (javax.xml.bind.annotation), this project also adds couple of its own annotations for convenience, to support XML-specific details:

  • @JacksonXmlElementWrapper allows specifying XML element to use for wrapping List and Map properties
  • @JacksonXmlProperty allows specifying XML namespace and local name for a property; as well as whether property is to be written as an XML element or attribute.
  • @JacksonXmlRootElement allows specifying XML element to use for wrapping the root element (default uses 'simple name' of the value class)
  • @JacksonXmlText allows specifying that value of one property is to be serialized as "unwrapped" text, and not in an element.
  • @JacksonXmlCData allows specifying that the value of a property is to be serialized within a CData tag.

for longer description, check out XML module annotations.

Known Limitations

Currently, following limitations exist beyond general Jackson (JSON) limitations:

  • Streaming model is only meant to be used through databinding: direct usage is possible but not supported
  • Tree Model (JsonNode, ObjectMapper.readTree()) is based on JSON content model and it does not match exactly with XML infoset
    • Mixed content (both textual content and elements as children of an element) not supported: text, if any, will be lost
    • Prior to 2.12, handling of repeated XML elements was problematic (it could only retain the last element read), but #403 improves handling
  • Root value should be a POJO (that is, a Java value expressed as a set of properties (key/value pairs)); and specifically following types can be serialized as properties but may not work as intended as root values
    • Primitive/Wrapper values (like java.lang.Integer)
    • Strings (and types that serialize as Strings such as Timestamps, Date/Time values)
    • Enums
    • Java arrays
    • java.util.Collection values (Lists, Sets)
    • Note: over time some level of support has been added, and Collections, for example, often work.
  • Lists and arrays are "wrapped" by default, when using Jackson annotations, but unwrapped when using JAXB annotations (if supported, see below)
    • @JacksonXmlElementWrapper.useWrapping can be set to 'false' to disable wrapping
    • JacksonXmlModule.setDefaultUseWrapper() can be used to specify whether "wrapped" or "unwrapped" setting is the default
  • Polymorphic Type Handling works, but only some of inclusion mechanisms are supported (WRAPPER_ARRAY, for example is not supported due to problems wrt mapping of XML, Arrays)
    • JAXB-style "compact" Type Id where property name is replaced with Type Id is not supported.
  • Mixed Content (elements and text in same element) is not supported in databinding: child content must be either text OR element(s) (attributes are fine)
  • While XML namespaces are recognized, and produced on serialization, namespace URIs are NOT verified when deserializing: only local names are matched
    • This also means that elements that only differ by namespace cannot be used.
  • Root name wrapping support is incomplete (SerializationFeature.WRAP_ROOT_VALUE / DeserializationFeature.UNWRAP_ROOT_VALUE, so that:
    • Serialization DOES NOT add wrapping (at least up to and including 2.13)
    • Deserialization DOES unwrap root element (except for Jackson 2.12.x that temporarily removed support altogether -- fixed in 2.13.0)

Support

Community support

Jackson components are supported by the Jackson community through mailing lists, Gitter forum, Github issues. See Participation, Contributing for full details.

Enterprise support

Available as part of the Tidelift Subscription.

The maintainers of jackson-dataformat-xml and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.


See Also

More Repositories

1

jackson

Main Portal page for the Jackson project
9,099
star
2

jackson-databind

General data-binding package for Jackson (2.x): works on streaming API (core) implementation(s)
Java
3,522
star
3

jackson-core

Core part of Jackson that defines Streaming API as well as basic shared abstractions
Java
2,263
star
4

jackson-module-kotlin

Module that adds support for serialization/deserialization of Kotlin (http://kotlinlang.org) classes and data classes.
Kotlin
1,123
star
5

jackson-annotations

Core annotations (annotations that only depend on jackson-core) for Jackson data processor
Java
1,029
star
6

jackson-docs

Documentation for the Jackson JSON processor.
727
star
7

jackson-module-scala

Add-on module for Jackson (https://github.com/FasterXML/jackson) to support Scala-specific datatypes
Scala
501
star
8

jackson-dataformats-text

Uber-project for (some) standard Jackson textual format backends: csv, properties, yaml (xml to be added in future)
Java
405
star
9

jackson-modules-java8

Set of support modules for Java 8 datatypes (Optionals, date/time) and features (parameter names)
Java
400
star
10

jackson-module-jsonSchema

Module for generating JSON Schema (v3) definitions from POJOs
Java
369
star
11

jackson-datatype-hibernate

Add-on module for Jackson JSON processor which handles Hibernate (https://www.hibernate.org/) datatypes; and specifically aspects of lazy-loading
Java
318
star
12

jackson-dataformats-binary

Uber-project for standard Jackson binary format backends: avro, cbor, ion, protobuf, smile
Java
313
star
13

aalto-xml

Ultra-high performance non-blocking XML processor (Stax API + extensions)
Java
292
star
14

java-classmate

Library for introspecting generic type information of types, member/static methods, fields. Especially useful for POJO/Bean introspection.
Java
258
star
15

jackson-jr

Stand-alone data-binding module designed as a light-weight (and -featured) alternative to `jackson-databind`: will only deal with "Maps, Lists, Strings, wrappers and Java Beans" (jr-objects), or simple read-only trees (jr-stree)
Java
239
star
16

woodstox

The gold standard Stax XML API implementation. Now at Github.
Java
226
star
17

jackson-dataformat-csv

(DEPRECATED) -- moved under: https://github.com/FasterXML/jackson-dataformats-text
Java
194
star
18

jackson-modules-base

Uber-project for foundational modules of Jackson that build directly on core components but nothing else; not including data format or datatype modules
Java
167
star
19

jackson-datatype-joda

Extension module to properly support full datatype set of Joda datetime library
Java
140
star
20

jackson-dataformat-yaml

Jackson module to add YAML backend (parser/generator adapters)
Java
138
star
21

jackson-jaxrs-providers

Multi-module project that contains Jackson-based "old" JAX-RS (ones under `javax.ws.rs`) providers for JSON, XML, YAML, Smile, CBOR formats
Java
111
star
22

smile-format-specification

New home for Smile format (https://en.wikipedia.org/wiki/Smile_(data_interchange_format))
92
star
23

jackson-datatype-jsr310

(DEPRECATED) -- moved under `jackson-modules-java8` repo: https://github.com/FasterXML/jackson-modules-java8
Java
92
star
24

jackson-module-afterburner

(DEPRECATED) -- moved under `jackson-modules-base`
Java
91
star
25

jackson-datatypes-collections

Jackson project that contains various collection-oriented datatype libraries: Eclipse Collections, Guava, HPPC, PCollections
Java
77
star
26

jackson-datatype-guava

(DEPRECATED) -- moved under `jackson-datatypes-collections`
Java
68
star
27

jackson-datatype-jdk8

(DEPRECATED) -- moved under `jackson-modules-java8`
Java
57
star
28

jackson-bom

Bill of materials POM for Jackson projects
Logos
54
star
29

jackson-datatype-json-org

(DEPRECATED) Support for org.json data types, to ease migration out of code that uses them
Java
49
star
30

jackson-dataformat-smile

(DEPRECATED) -- moved under `jackson-dataformats-binary
Java
44
star
31

jackson-module-jaxb-annotations

(DEPRECATED!!!) Moved to: https://github.com/FasterXML/jackson-modules-base/
Java
44
star
32

StaxMate

StaxMate: Automatic Shifting for Streaming XML Processing
Java
41
star
33

stax2-api

Extension API for Stax, Java pull-parsing API (STreaming Api for Xml)
Java
40
star
34

jackson-dataformat-cbor

(DEPRECATED) -- moved under `jackson-dataformats-binary`
Java
38
star
35

jackson-dataformat-avro

(DEPRECATED) -- moved under `jackson-dataformats-binary
Java
38
star
36

jackson-module-parameter-names

(DEPRECATED) -- moved under `jackson-modules-java8`
Java
33
star
37

jackson-dataformat-protobuf

(DEPRECATED) -- moved under `jackson-dataformats-binary`
Java
32
star
38

jackson-module-mrbean

(DEPRECATED) -- moved under `jackson-modules-base`
Java
27
star
39

jackson-datatypes-misc

Collection of common Jackson datatype modules not part of other multi-project repos
Java
22
star
40

TransiStore

Distributed data store for transient (temporary, time-bound) data. Based on ClusterMate/StoreMate
Java
21
star
41

jackson-datatype-jsr353

(DEPRECATED) -- moved under `jackson-datatypes-misc` https://github.com/FasterXML/jackson-datatypes-misc/
Java
19
star
42

jackson-future-ideas

Repository for SOLE PURPOSE of issue tracker and Wiki for NEW IDEAS. Please: NO BUG REPORTS.
18
star
43

jackson-benchmarks

Project that contains JMH-based micro-benchmarks to help with optimizations
Java
15
star
44

jackson-jakarta-rs-providers

Multi-module project that contains Jackson-based "new" Jakarta-RS (nee "JAX-RS" -- ones under `jakarta.ws.rs`) providers for JSON, XML, YAML, Smile, CBOR formats
Java
14
star
45

jackson-dataformat-properties

(DEPRECATED) -- moved under `jackson-dataformats-text`
Java
13
star
46

jackson-datatype-hppc

(DEPRECATED) -- moved under `jackson-datatypes-collections`
Java
9
star
47

oss-parent

Grandpa pom for all projects under FasterXML git umbrella
8
star
48

jackson-datatype-jdk7

(DEPRECATED) -- included in `jackson-databind` as of Jackson 2.7
Java
7
star
49

jvm-json-benchmark

Performance benchmark suite that compares data-binding (JSON<->POJO) performance of Java JSON libraries. Uses Japex benchmark framework for running tests and visualizing results.
Java
7
star
50

Hacktoberfest2020

Central repository for FasterXML activities related to Hacktoberfest 2020 by DigitalOcean (https://hacktoberfest.digitalocean.com/)
6
star
51

jackson-module-guice

(DEPRECATED) -- moved under `jackson-modules-base`
Java
5
star
52

jackson3-dev

Repository for planning and tracking development of Jackson 3.0, with bigger API changes
5
star
53

jackson-module-paranamer

(DEPRECATED) -- moved under `jackson-modules-base`
Java
5
star
54

jackson-parent

Parent pom for all core Jackson components (but only those -- users should use `jackson-bom`)
5
star
55

jackson-schema-maven-plugin

Maven plug-in for generation JSON Schemas using Jackson library and extension modules
Java
4
star
56

jackson-jdk11-compat-test

Test project for verifying Jackson's support of JDK9+ Module system
Java
3
star
57

jackson-dataformat-thrift

Not Yet A Thing -- placeholder for possible future implementation
Java
3
star
58

jackson-integration-tests

Project that contains integration tests across Jackson components
Java
3
star
59

jackson-jdk17-compat-test

Test suite for JDK 16 compatibility of Jackson components, mainly jackson-databind
Java
3
star
60

jackson-tools

Collection of command-line tools related to Jackson data processor, such as format decoders
Java
2
star
61

jackson-dataformat-ini

(Not Yet a Thing -- Placholder!) Data format implementation for "ini files", used on Windows, Python
Java
2
star
62

OmniPipe

Distributed data queue implementation that builds on ClusterMate/StoreMate foundation
2
star
63

jackson-jdk6-compat-test

Test project to verify JDK6 compatibility of Jackson versions 2.7 and anbove
Java
2
star
64

jackson-module-osgi

(DEPRECATED) -- moved under `jackson-modules-base`
Java
2
star
65

jackson-gh-actions

Repository for reusable Github workflow actions for Jackson project
2
star
66

Woodstox4

Backup repository for older versions of Woodstox (pre-5.0), migrated from Codehaus
Java
1
star