杰瑞科技汇

Java如何将JSON转换为XML?

Of course! Converting JSON to XML in Java is a common task, and there are several excellent libraries to achieve this. I'll cover the most popular and robust options, from simple one-liners to more flexible, configurable solutions.

Java如何将JSON转换为XML?-图1
(图片来源网络,侵删)

Summary of Options

Library Pros Cons Best For
Jackson High performance, widely used, flexible configuration, good error handling. Can be complex for simple tasks. Most production applications, REST APIs, performance-critical systems.
Gson Simple, easy-to-use API, good for basic conversions. Less powerful configuration for XML compared to Jackson. Quick and simple conversions when you're already using Gson for JSON.
Simple Extremely simple, no dependencies, good for basic needs. Not very flexible, limited configuration, less performant. Projects with minimal dependencies or very simple, predictable JSON structures.
XStream Very flexible, can handle complex object mappings, annotations. Can be considered overkill for simple tasks, has security considerations. Complex object graphs, when you need fine-grained control over the XML output.

Option 1: Jackson (Recommended)

Jackson is the de-facto standard for JSON processing in Java. Its jackson-dataformat-xml module provides a powerful and highly configurable way to convert between JSON and XML.

Step 1: Add Dependency

You need to add the Jackson XML dataformat module to your project.

Maven (pom.xml):

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.15.2</version> <!-- Use the latest version -->
</dependency>

(Note: Jackson core and databind are usually transitive dependencies, but you should include them if you have any issues.)

Java如何将JSON转换为XML?-图2
(图片来源网络,侵删)

Gradle (build.gradle):

implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.15.2' // Use the latest version

Step 2: Write the Java Code

The process involves creating an ObjectMapper configured for XML and using its readValue and writeValue methods.

Let's use a sample JSON string and a corresponding Java class (POJO).

Sample JSON (data.json):

Java如何将JSON转换为XML?-图3
(图片来源网络,侵删)
{
  "name": "John Doe",
  "age": 30,
  "isStudent": false,
  "address": {
    "street": "123 Main St",
    "city": "Anytown"
  },
  "phoneNumbers": [
    "555-1234",
    "555-5678"
  ]
}

Java POJO (Person.java):

import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
import java.util.Map;
// Using @JsonProperty to map JSON keys to Java fields if they differ
public class Person {
    private String name;
    private int age;
    private boolean isStudent;
    private Address address;
    private List<String> phoneNumbers;
    // Nested static class for the address
    public static class Address {
        private String street;
        private String city;
        // Getters and Setters
        public String getStreet() { return street; }
        public void setStreet(String street) { this.street = street; }
        public String getCity() { return city; }
        public void setCity(String city) { this.city = city; }
    }
    // Getters and Setters
    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; }
    public boolean isStudent() { return isStudent; }
    public void setStudent(boolean student) { isStudent = student; }
    public Address getAddress() { return address; }
    public void setAddress(Address address) { this.address = address; }
    public List<String> getPhoneNumbers() { return phoneNumbers; }
    public void setPhoneNumbers(List<String> phoneNumbers) { this.phoneNumbers = phoneNumbers; }
}

Main Conversion Class:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import java.io.File;
import java.io.IOException;
public class JsonToXmlConverter {
    public static void main(String[] args) {
        String jsonString = """
            {
              "name": "John Doe",
              "age": 30,
              "isStudent": false,
              "address": {
                "street": "123 Main St",
                "city": "Anytown"
              },
              "phoneNumbers": [
                "555-1234",
                "555-5678"
              ]
            }
            """;
        try {
            // 1. Create an ObjectMapper with the XML module
            ObjectMapper xmlMapper = new XmlMapper();
            // 2. (Optional) Configure the mapper for pretty printing
            xmlMapper.enable(SerializationFeature.INDENT_OUTPUT);
            // 3. Convert JSON string to Java Object (POJO)
            Person person = xmlMapper.readValue(jsonString, Person.class);
            // 4. Convert Java Object to XML string
            String xmlString = xmlMapper.writeValueAsString(person);
            System.out.println("--- Converted to XML ---");
            System.out.println(xmlString);
            // You can also write the XML directly to a file
            xmlMapper.writeValue(new File("person.xml"), person);
            System.out.println("\nXML has been written to person.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Expected XML Output:

<?xml version="1.0" encoding="UTF-8"?>
<Person>
  <name>John Doe</name>
  <age>30</age>
  <isStudent>false</isStudent>
  <address>
    <street>123 Main St</street>
    <city>Anytown</city>
  </address>
  <phoneNumbers>555-1234</phoneNumbers>
  <phoneNumbers>555-5678</phoneNumbers>
</Person>

Option 2: Gson (Simpler Alternative)

Google's Gson is another popular library for JSON. While its primary focus is JSON, it can be used for simple conversions if you add an XML writer.

Step 1: Add Dependency

Maven (pom.xml):

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.10.1</version> <!-- Use the latest version -->
</dependency>

You'll also need a library to convert the Gson JsonElement tree to XML. json-xml is a good choice.

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20251013</version> <!-- Use the latest version -->
</dependency>

Step 2: Write the Java Code

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import org.json.JSONObject;
import org.json.XML;
public class GsonJsonToXmlConverter {
    public static void main(String[] args) {
        String jsonString = """
            {
              "name": "Jane Doe",
              "age": 28,
              "isStudent": false,
              "address": {
                "street": "456 Oak Ave",
                "city": "Otherville"
              }
            }
            """;
        try {
            // 1. Parse JSON string into a JsonElement tree using Gson
            Gson gson = new Gson();
            JsonElement jsonElement = JsonParser.parseString(jsonString);
            // 2. Convert JsonElement to a org.json.JSONObject
            // This is a bit of a workaround, but it works.
            String jsonObjectString = gson.toJson(jsonElement);
            JSONObject jsonObject = new JSONObject(jsonObjectString);
            // 3. Convert JSONObject to XML string
            // The second argument (true) specifies if the output should be pretty-printed
            String xmlString = XML.toString(jsonObject, true);
            System.out.println("--- Converted to XML ---");
            System.out.println(xmlString);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Expected XML Output:

<?xml version="1.0" encoding="UTF-8"?>
<o>
  <name>Jane Doe</name>
  <age>28</age>
  <isStudent>false</isStudent>
  <address>
    <street>456 Oak Ave</street>
    <city>Otherville</city>
  </address>
</o>

Note: Gson's approach is less direct and requires an extra step to convert to org.json.JSONObject for a clean XML conversion.


Option 3: Simple (No Dependencies)

This approach uses the built-in javax.xml.bind package (JAXB), which is included in the Java Standard Edition (JSE) since Java 6. It's great if you want to avoid external libraries but requires a bit more setup.

Step 1: Define the Java Class (POJO)

The class must be annotated with JAXB annotations.

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;
@XmlRootElement(name = "person") // This will be the root element of the XML
public class PersonSimple {
    @XmlElement(name = "name")
    private String name;
    @XmlElement(name = "age")
    private int age;
    @XmlElement(name = "isStudent")
    private boolean isStudent;
    @XmlElement(name = "address")
    private AddressSimple address;
    @XmlElement(name = "phoneNumbers")
    private List<String> phoneNumbers;
    // Nested static class
    public static class AddressSimple {
        @XmlElement(name = "street")
        private String street;
        @XmlElement(name = "city")
        private String city;
        // Getters and Setters (required by JAXB)
        public String getStreet() { return street; }
        public void setStreet(String street) { this.street = street; }
        public String getCity() { return city; }
        public void setCity(String city) { this.city = city; }
    }
    // Getters and Setters (required by JAXB)
    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; }
    public boolean isStudent() { return isStudent; }
    public void setStudent(boolean student) { isStudent = student; }
    public AddressSimple getAddress() { return address; }
    public void setAddress(AddressSimple address) { this.address = address; }
    public List<String> getPhoneNumbers() { return phoneNumbers; }
    public void setPhoneNumbers(List<String> phoneNumbers) { this.phoneNumbers = phoneNumbers; }
}

Step 2: Write the Conversion Code

You need a library to parse JSON into your POJO first. Since we're avoiding dependencies, we'll do a manual string replacement for this simple example. This is not robust for real-world use.

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.StringWriter;
public class SimpleJsonToXmlConverter {
    public static void main(String[] args) {
        // WARNING: This is a very naive JSON-to-POJO conversion for demonstration only.
        // In a real app, use a library like Jackson or Gson for this step.
        String jsonString = """
            {
              "name": "Peter Jones",
              "age": 45,
              "isStudent": false,
              "address": {
                "street": "789 Pine Ln",
                "city": "Newburg"
              },
              "phoneNumbers": [
                "555-9999"
              ]
            }
            """;
        // Manually creating the object (NOT recommended for production)
        PersonSimple person = new PersonSimple();
        person.setName("Peter Jones");
        person.setAge(45);
        person.setStudent(false);
        PersonSimple.AddressSimple address = new PersonSimple.AddressSimple();
        address.setStreet("789 Pine Ln");
        address.setCity("Newburg");
        person.setAddress(address);
        // Convert POJO to XML using JAXB
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(PersonSimple.class);
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
            // Format the XML output
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            StringWriter stringWriter = new StringWriter();
            jaxbMarshaller.marshal(person, stringWriter);
            System.out.println("--- Converted to XML ---");
            System.out.println(stringWriter.toString());
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }
}

Expected XML Output:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<person>
    <name>Peter Jones</name>
    <age>45</age>
    <isStudent>false</isStudent>
    <address>
        <street>789 Pine Ln</street>
        <city>Newburg</city>
    </address>
    <phoneNumbers>555-9999</phoneNumbers>
</person>

Recommendation

For most Java applications, Jackson is the best choice. It's powerful, performant, and flexible. It handles the JSON-to-POJO and POJO-to-XML steps seamlessly, giving you full control over the process.

Choose Gson if your project is already heavily reliant on it and you need a quick, simple conversion.

Choose the Simple/JAXB approach only if you are in a strict environment where you cannot add third-party libraries and your JSON structures are very simple and predictable.

分享:
扫描分享到社交APP
上一篇
下一篇