Generate JSON data using Java class annotated with JAXB annotation, using Jackson library

Although Java classes are annotated using annotations from the JAXB library, they will be used to generate XML data. However, in some cases, you will need to generate JSON data instead of XML using these Java classes. To do this, you can use the Jackson library with jackson-module-jaxb-annotations for the Java EE namespace, or jackson-module-jakarta-xmlbind-annotations for the Jakarta EE namespace. How is it in detail? Let’s find out together in this tutorial!

I will create a new Maven project:

for example.

I will use the Jakarta EE namespace so I will declare the JAXB and jackson-module-jakarta-xmlbind-annotations dependencies as follows:

As an example, I have a Student class annotated with JAXB library annotations as follows:

I will initialize a Student object with the following information:

To generate Student object information in JSON format, first, I will initialize the ObjectMapper object as follows:

Next, we need to enable Jakarta XML Binding support for the ObjectMapper object using the JakartaXmlBindAnnotationIntrospector class, in one of the following two ways:

or:

and now, we will use the writeValueAsString() method of the ObjectMapper object to convert the Student object to a JSON string:

My entire code is as follows:

The result when I run my example is as follows:

Add Comment