Convert XML file to JSON in Java Using JAXB with annotations and Google Gson Tutorial

Overview

In this tutorial, we show you how to convert XML file to JSON in Java using JAXB with annotations and Google Gson data binding API Gson.

Convert XML file to JSON in Java Using JAXB

Follow the steps mentioned below to develop this application.

Watch Tutorial




Project Structure


Project Structure ConvertXmlToJsonUsingGsonAndJAXB

Create Maven Project

  • Launch Eclipse IDE.
  • Go to File-> New-> Others... Select Maven Project under Maven category then click Next.
  • In New Maven Project wizard, select "Create a simpel project(skip archetype selection)" and click on Next
  • In next wizard, type "com.jackrutorial" in the "Group ID:" field
  • Type "ConvertXmlToJsonUsingGsonJAXB" in the "Artifact Id:" field
  • Packaging -> War
  • Click Finish.

Update pom.xml to include required dependencies

Open pom.xml file and add the following dependencies in it.

<project xmlns="http://maven.apache.org/POM/4.0.0" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.jackrutorial</groupId>
 <artifactId>ConvertXmlToJsonUsingGsonJAXB</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>jar</packaging>

 <dependencies>
  <dependency>
   <groupId>com.google.code.gson</groupId>
   <artifactId>gson</artifactId>
   <version>2.8.2</version>
  </dependency>
  <dependency>
   <groupId>javax.xml.bind</groupId>
   <artifactId>jaxb-api</artifactId>
   <version>2.3.0</version>
  </dependency>
 </dependencies>

 <build>
  <sourceDirectory>src</sourceDirectory>
  <plugins>
   <plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>2.4</version>
    <configuration>
     <source />
     <target />
    </configuration>
   </plugin>
  </plugins>
 </build>

</project>

Create users.xml file in Project Location


<users>
 <user>
  <name>Test 1</name>
  <age>25</age>
 </user>
 <user>
  <name>Test 2</name>
  <age>26</age>
 </user>
</users>

Create JAXB Annotation

XmlRootElement – This is added to the class and will map the class to the XML.
XmlElement – This used to methods or property and will map the property to an XML element.

Create a User class under com.jackrutorial.bean package and write the following code in it.

User.java

package com.jackrutorial.bean;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "user")
@XmlAccessorType(XmlAccessType.FIELD)
public class User {
 
 private String name;
 private int age;
 
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
}

Create a Users class under com.jackrutorial.bean package and write the following code in it.

Users.java
package com.jackrutorial.bean;

import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="users")
@XmlAccessorType(XmlAccessType.FIELD)
public class Users {
 
 @XmlElement(name="user")
 private List<User> users = null;

 public List<User> getUsers() {
  return users;
 }

 public void setUsers(List<User> users) {
  this.users = users;
 }
}


Create Main Class


Create a Main class under com.jackrutorial.main package and write the following code in it.

First, we will convert a users.xml file content into a users object using JAXB unmarshalling. Then we will convert Java Object to Json using Google Gson data binding API Gson.

package com.jackrutorial.main;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jackrutorial.bean.Users;

public class Main {

 public final static String XML_FILE = "users.xml";
 
 public static void main(String[] args) throws FileNotFoundException, JAXBException{
  Users users = convertXmlToObject(new FileInputStream(new File(XML_FILE)));
  System.out.println(convertObjectToJson(users));
 }
 
 public static Users convertXmlToObject(InputStream in) throws JAXBException{
  JAXBContext jaxbContext = JAXBContext.newInstance(Users.class);
  Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
  
  return (Users) unmarshaller.unmarshal(in);
 }
 
 public static String convertObjectToJson(Users user){
  GsonBuilder gsonBuilder = new GsonBuilder();
  gsonBuilder.setPrettyPrinting();
  gsonBuilder.disableHtmlEscaping();
  
  Gson gson = gsonBuilder.create();
  return gson.toJson(user, Users.class);
 }
 
}

Run & Check result

  • Right click to the ConvertObjectToJson class, select Run As -> Java Application

Output


{
  "users": [
    {
      "name": "Test 1",
      "age": 25
    },
    {
      "name": "Test 2",
      "age": 26
    }
  ]
}

Required Libraries

Previous Post
Next Post

post written by: