How to Parse JSON & XML Using the Same Code in Java
Jackson dataformat in practice
Supporting multiple formats like XML (Extensible Markup Language) and JSON (JavaScript Object Notation) usually means multiple implementations that deal with serializing and deserializing data. Fortunately, it’s possible to do it using the same code.
In this article, you’ll learn how to do it in Java by using dataformat-xml — Jackson library extension in such a way that you only need to write your code once. We’ll go through the main features including model definition, custom serialization, and deserialization. Finally, I’ll share a tricky use-case where our “one to rule them all code” won’t work and explain why.
Project setup
We’ll use a simple Maven project. In the pom.xml build section, there is a maven-compiler-plugin configured to use Java 11. We’ll also need jackson-dataformat-xml dependency.
For your production code make sure you also use Woodstox-core as according to documentation it’s much faster than JDK’s Stax…