Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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

License

NotificationsYou must be signed in to change notification settings

FasterXML/jackson-dataformat-xml

 
 

Repository files navigation

This projects containsJackson extension component forreading and writingXML encoded data.

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

It is worth noting, however, that the goal is NOT to be full JAXB clone; or to be ageneral 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 this module will not be able to handle; including some cases JAXB (and other Java XML libraries) support
  • This module also supports constructs and use cases JAXB does not handle: specifically, rich type and object id support of Jackson are supported.

Status

TypeStatus
Build (CI)Build (github)
ArtifactMaven Central
OSS SponsorshipTidelift
JavadocsJavadoc
Code coverage (2.19)codecov.io
OpenSSF ScoreOpenSSF  Scorecard
FuzzingFuzzing Status

Branches

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

  • 2.19 is for developing the next minor 2.x version
  • 2.18 is for backported fixes to include in 2.18.x patch versions
  • 2.17 is for backported fixes to include in 2.17.x patch versions

Older branches are usually not changed but are available for historic reasons.All released versions have matching git tags (jackson-dataformat-xml-2.17.1).

License

All modules are licensed underApache 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.18.1</version></dependency>

Gradle:

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

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

Also: you usually also want to make sure the XML library in use isWoodstox 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 yourpom.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 this module implements low-level (JsonFactory /JsonParser /JsonGenerator) abstractions,most usage is through data-binding level. This is because a small number of work-arounds have been addedat data-binding level, to work around XML peculiarities: that is, the stream ofJsonTokens that the parserproduces has idiosyncracies that need special handling.

Usually you either createXmlMapper simply by:

XmlMappermapper =newXmlMapper();

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

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

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

XMLInputFactoryifactory =newWstxInputFactory();// Woodstox XMLInputFactory implifactory.setProperty(WstxInputProperties.P_MAX_ATTRIBUTE_SIZE,32000);// configureXMLOutputFactoryofactory =newWstxOutputFactory();// Woodstox XMLOutputfactory implofactory.setProperty(WstxOutputProperties.P_OUTPUT_CDATA_AS_TEXT,true);XmlFactoryxf =XmlFactory.builder()    .xmlInputFactory(ifactory)// note: in 2.12 and before "inputFactory()"    .xmlOutputFactory(ofactory)// note: in 2.12 and before "outputFactory()"    .builder();XmlMappermapper =newXmlMapper(xf);// there are other overloads too

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

As the well as the Woodstox properties specified above, you can also callWstxInputFactory#getConfig()and modify theReaderConfig.One useful setting is themaxElementDepth.

Android quirks

Use of this library on Android is supported since version 2.15.0 (partly via fix of#533).

Earlier versions had problem due to Stax API being unavailable on the Android platform, and attempts to declare an explicit dependency on the Stax API library resulting in errors at build time (since the inclusion of thejavax.* namespace in apps is restricted).For more on this old issue, see:

Serializing POJOs as XML

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

// Important: create XmlMapper; it will use proper factories, workaroundsObjectMapperxmlMapper =newXmlMapper();Stringxml =xmlMapper.writeValueAsString(newSimple());// orxmlMapper.writeValue(newFile("/tmp/stuff.xml"),newSimple());

and with POJO like:

publicclassSimple {publicintx =1;publicinty =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:

ObjectMapperxmlMapper =newXmlMapper();Simplevalue =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 StaxXMLInputFactory separately (similar to how with JSON you would createJsonGenerator), and then:

// First create Stax components we needXMLInputFactoryxmlInputFactory =XMLInputFactory.newFactory();XMLOutputFactoryxmlOutputFactory =XMLOutputFactory.newFactory();StringWriterout =newStringWriter();XMLStreamWritersw =xmlOutputFactory.createXMLStreamWriter(out);// then Jackson componentsXmlMappermapper =newXmlMapper(xmlInputFactory);sw.writeStartDocument();sw.writeStartElement("root");// Write whatever content POJOs...SomePojovalue1 = ...;OtherPojovalue2 = ...;mapper.writeValue(sw,value1);mapper.writeValue(sw,value2);// and/or regular Stax outputsw.writeComment("Some insightful commentary here");sw.writeEndElement();sw.writeEndDocument();

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

XMLInputFactoryf =XMLInputFactory.newFactory();FileinputFile = ...;XMLStreamReadersr =f.createXMLStreamReader(newFileInputStream(inputFile));XmlMappermapper =newXmlMapper();sr.next();// to point to <root>sr.next();// to point to root-element under rootSomePojovalue1 =mapper.readValue(sr,SomePojo.class);// sr now points to matching END_ELEMENT, so move forwardsr.next();// should verify it's either closing root or new start, left as exerciseOtherPojovalue =mapper.readValue(sr,OtherPojo.class);// and more, as needed, thensr.close();

Additional annotations

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

  • @JacksonXmlElementWrapper allows specifying XML element to use for wrappingList andMap 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 a longer description, check outXML 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 to2.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 (likejava.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, andCollections, 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 inclusion mechanisms are supported (WRAPPER_ARRAY, for example is not supported due to problems with reference to 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. SeeParticipation, Contributing for full details.

Enterprise support

Available as part of the Tidelift Subscription.

The maintainers ofjackson-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

About

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

Resources

License

Security policy

Stars

Watchers

Forks

Sponsor this project

    Packages

    No packages published

    [8]ページ先頭

    ©2009-2025 Movatter.jp