Lesson 5: Support both XML and JSON

1. Goal

Learn the basics of Content Negotiation and enable XML support for the API in Spring (starting with Spring 4.1).


2. Lesson Notes

The relevant module you need to import when you're starting with this lesson is: m2-lesson5-start

If you want to have a look at the fully implemented lesson, as a reference, feel free to import: m2-lesson5


The Maven Dependencies

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
</dependency>
<dependency>
    <groupId>org.codehaus.woodstox</groupId>
    <artifactId>woodstox-core-asl</artifactId>
    <version>4.4.1</version>
</dependency>


Advantages of using Jackson for XML

Using the new Jackson Spring support for XML has quite a few advantages over using another XML library (such as XStream):

  • we're already using Jackson for JSON
  • we can re-use the exact same configuration that we're already using for JSON
  • no need to add extra annotations to the DTOs
  • JSON Views support


Why change the default STAX implementation

Woodstox has a few advantages over the default STAX impl in the JDK:

  • it's faster
  • has extra features
  • it's more mature and well maintained


Basics of Content Negotiation

- a JSON Request:

GET http://localhost:8082/api/privileges
Accept: application/json
[ {
  "id" : 1,
  "name" : "ROLE_PRIVILEGE_READ",
  "description" : null
}, 
... ]

- an XML Request:

GET http://localhost:8082/api/privileges
Accept: application/xml
<List>
  <item>
    <id>1</id>
    <name>ROLE_PRIVILEGE_READ</name>
    <description/>
  </item>
  ...
</List>


Quick note - starting with Spring 4.3.2, we now have support for multiple Accept headers in the HeaderContentNegotiationStrategy.

Upgrade Notes

As mentioned, the woodstox-core-asl dependency which is used for XML processing is a mature and well-maintained library. However, note that the newer versions of the dependency have a different group and artifact id:

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


3. Resources

- Content negotiation


RwS - Support both XML and JSON - transcript.pdf
Complete and Continue