Java XML and JSON Processing
XML (eXtensible Markup Language) and JSON (JavaScript Object Notation) are the most popular data exchange formats today. Whether calling web services, reading configuration files, or transferring data between different systems, they are indispensable. This chapter introduces common methods for processing these two formats in Java.
Processing XML
XML is a tag-based markup language with a rigorous structure, once widely used for configuration files and SOAP web services. Java provides multiple APIs for processing XML.
JAXB (Java Architecture for XML Binding)
JAXB is a powerful API that can marshal Java objects into XML and unmarshal XML back into Java objects, achieving automatic mapping between objects and XML.
To use JAXB, you need to define a Java class that matches the XML structure and mark it with JAXB annotations.
// 1. Define a Java class with JAXB annotations
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlElement;
@XmlRootElement
public class Customer {
private String name;
private int age;
@XmlElement
public void setName(String name) { this.name = name; }
public String getName() { return name; }
@XmlElement
public void setAge(int age) { this.age = age; }
public int getAge() { return age; }
}// 2. Marshalling (Java Object -> XML)
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import java.io.File;
public class JaxbMarshalExample {
public static void main(String[] args) throws Exception {
Customer customer = new Customer();
customer.setName("John Doe");
customer.setAge(30);
JAXBContext context = JAXBContext.newInstance(Customer.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // Format output
// Output to console
marshaller.marshal(customer, System.out);
// Output to file
marshaller.marshal(customer, new File("customer.xml"));
}
}
// Output XML:
// <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
// <customer>
// <age>30</age>
// <name>John Doe</name>
// </customer>Note: Starting from Java 9, JAXB is no longer part of the standard library and needs to be added as a separate dependency to the project.
Processing JSON
JSON is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. It has become the de facto standard for RESTful APIs.
The Java standard library does not have a built-in JSON processing API, but there are many excellent third-party libraries available, the most popular being:
- Jackson: Very powerful with excellent performance, the default choice for many mainstream frameworks like Spring.
- Gson: Developed by Google, with a simple and easy-to-use API, very suitable for simple JSON-object mapping.
Using Jackson
Jackson's core component is ObjectMapper, which can easily convert between Java objects and JSON strings.
// 1. Define a simple POJO (Plain Old Java Object)
public class Car {
private String brand;
private int doors;
// Needs getters, setters, and a no-argument constructor
public Car() {}
public Car(String brand, int doors) { this.brand = brand; this.doors = doors; }
public String getBrand() { return brand; }
public void setBrand(String brand) { this.brand = brand; }
public int getDoors() { return doors; }
public void setDoors(int doors) { this.doors = doors; }
}// 2. Serialization (Java Object -> JSON) and Deserialization (JSON -> Java Object)
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonExample {
public static void main(String[] args) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
// --- Serialization ---
Car car = new Car("Toyota", 4);
String jsonString = objectMapper.writeValueAsString(car);
System.out.println("Serialized JSON: " + jsonString);
// Output: {"brand":"Toyota","doors":4}
// --- Deserialization ---
String jsonToParse = "{\"brand\":\"Ford\",\"doors\":2}";
Car parsedCar = objectMapper.readValue(jsonToParse, Car.class);
System.out.println("Deserialized brand: " + parsedCar.getBrand()); // Output: Ford
}
}Using Gson
Gson's usage is similar to Jackson, mainly operating through the Gson class.
import com.google.gson.Gson;
public class GsonExample {
public static void main(String[] args) {
Gson gson = new Gson();
// --- Serialization ---
Car car = new Car("Honda", 4);
String jsonString = gson.toJson(car);
System.out.println("Serialized JSON: " + jsonString);
// Output: {"brand":"Honda","doors":4}
// --- Deserialization ---
String jsonToParse = "{\"brand\":\"BMW\",\"doors\":2}";
Car parsedCar = gson.fromJson(jsonToParse, Car.class);
System.out.println("Deserialized brand: " + parsedCar.getBrand()); // Output: BMW
}
}Which library to choose usually depends on the project's requirements. For complex projects requiring high customization and best performance, Jackson is the better choice. For simple data binding tasks, Gson's simplicity may be more appealing.