java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java JSON与XML互转

Java实现JSON与XML相互转换的简明教程

作者:promise524

Java实现复杂数据结构(如嵌套对象、数组)在 JSON 与 XML 之间的相互转换,可以使用 Jackson 和 Jackson XML 扩展库来完成,Jackson 是一个流行的 JSON 处理库,通过 Jackson 的 XML 扩展库,可以实现 JSON 和 XML 之间的转换,需要的朋友可以参考下

前言

Java实现复杂数据结构(如嵌套对象、数组)在 JSON 与 XML 之间的相互转换,可以使用 JacksonJackson XML 扩展库来完成。Jackson 是一个流行的 JSON 处理库,支持将 Java 对象序列化为 JSON 字符串,并反序列化为 Java 对象。通过 Jackson 的 XML 扩展库,可以实现 JSON 和 XML 之间的转换。

引入依赖

<dependencies>
    <!-- Jackson Core -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.15.0</version>
    </dependency>

    <!-- Jackson Databind -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.15.0</version>
    </dependency>

    <!-- Jackson Dataformat XML -->
    <dependency>
        <groupId>com.fasterxml.jackson.dataformat</groupId>
        <artifactId>jackson-dataformat-xml</artifactId>
        <version>2.15.0</version>
    </dependency>
</dependencies>

实现 XML 和 JSON 互转

定义数据结构

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;

import java.util.List;

// 员工类
public class Employee {
    private String name;
    private int age;
    private String role;

    public Employee() { }

    public Employee(String name, int age, String role) {
        this.name = name;
        this.age = age;
        this.role = role;
    }

    // Getters and Setters
    @JacksonXmlProperty(localName = "Name")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @JacksonXmlProperty(localName = "Age")
    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @JacksonXmlProperty(localName = "Role")
    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }
}

// 部门类
public class Department {
    private String name;
    private List<Employee> employees;

    public Department() { }

    public Department(String name, List<Employee> employees) {
        this.name = name;
        this.employees = employees;
    }

    // Getters and Setters
    @JacksonXmlProperty(localName = "Name")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @JacksonXmlElementWrapper(localName = "Employees")
    @JacksonXmlProperty(localName = "Employee")
    public List<Employee> getEmployees() {
        return employees;
    }

    public void setEmployees(List<Employee> employees) {
        this.employees = employees;
    }
}

// 公司类
public class Company {
    private String name;
    private List<Department> departments;

    public Company() { }

    public Company(String name, List<Department> departments) {
        this.name = name;
        this.departments = departments;
    }

    // Getters and Setters
    @JacksonXmlProperty(localName = "Name")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @JacksonXmlElementWrapper(localName = "Departments")
    @JacksonXmlProperty(localName = "Department")
    public List<Department> getDepartments() {
        return departments;
    }

    public void setDepartments(List<Department> departments) {
        this.departments = departments;
    }
}

JSON 与 XML 互转实现

JSON 转 XML

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

import java.io.IOException;
import java.util.Arrays;

public class JsonToXmlConverter {

    public static void main(String[] args) throws IOException {
        // 创建一个包含嵌套对象和数组的复杂结构的示例
        Employee emp1 = new Employee("Alice", 30, "Developer");
        Employee emp2 = new Employee("Bob", 28, "Designer");
        Department dept1 = new Department("IT", Arrays.asList(emp1, emp2));

        Employee emp3 = new Employee("Charlie", 32, "Manager");
        Department dept2 = new Department("HR", Arrays.asList(emp3));

        Company company = new Company("Tech Corp", Arrays.asList(dept1, dept2));

        // 将 Java 对象转换为 JSON 字符串
        ObjectMapper jsonMapper = new ObjectMapper();
        String jsonString = jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(company);
        System.out.println("JSON Representation:");
        System.out.println(jsonString);

        // 将 JSON 字符串转换为 XML 字符串
        XmlMapper xmlMapper = new XmlMapper();
        String xmlString = xmlMapper.writerWithDefaultPrettyPrinter().writeValueAsString(company);
        System.out.println("XML Representation:");
        System.out.println(xmlString);
    }
}

JSON 转 XML输出

<Company>
  <Name>Tech Corp</Name>
  <Departments>
    <Department>
      <Name>IT</Name>
      <Employees>
        <Employee>
          <Name>Alice</Name>
          <Age>30</Age>
          <Role>Developer</Role>
        </Employee>
        <Employee>
          <Name>Bob</Name>
          <Age>28</Age>
          <Role>Designer</Role>
        </Employee>
      </Employees>
    </Department>
    <Department>
      <Name>HR</Name>
      <Employees>
        <Employee>
          <Name>Charlie</Name>
          <Age>32</Age>
          <Role>Manager</Role>
        </Employee>
      </Employees>
    </Department>
  </Departments>
</Company>

XML 转 JSON

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

import java.io.IOException;

public class XmlToJsonConverter {

    public static void main(String[] args) throws IOException {
        // 假设已有 XML 字符串
        String xmlString = "<Company>\n" +
                "  <Name>Tech Corp</Name>\n" +
                "  <Departments>\n" +
                "    <Department>\n" +
                "      <Name>IT</Name>\n" +
                "      <Employees>\n" +
                "        <Employee>\n" +
                "          <Name>Alice</Name>\n" +
                "          <Age>30</Age>\n" +
                "          <Role>Developer</Role>\n" +
                "        </Employee>\n" +
                "        <Employee>\n" +
                "          <Name>Bob</Name>\n" +
                "          <Age>28</Age>\n" +
                "          <Role>Designer</Role>\n" +
                "        </Employee>\n" +
                "      </Employees>\n" +
                "    </Department>\n" +
                "    <Department>\n" +
                "      <Name>HR</Name>\n" +
                "      <Employees>\n" +
                "        <Employee>\n" +
                "          <Name>Charlie</Name>\n" +
                "          <Age>32</Age>\n" +
                "          <Role>Manager</Role>\n" +
                "        </Employee>\n" +
                "      </Employees>\n" +
                "    </Department>\n" +
                "  </Departments>\n" +
                "</Company>";

        // 将 XML 字符串转换为 Java 对象
        XmlMapper xmlMapper = new XmlMapper();
        Company company = xmlMapper.readValue(xmlString, Company.class);

        // 将 Java 对象转换为 JSON 字符串
        ObjectMapper jsonMapper = new ObjectMapper();
        String jsonString = jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(company);
        System.out.println("JSON Representation:");
        System.out.println(jsonString);
    }
}

XML 转 JSON 输出

{
  "name" : "Tech Corp",
  "departments" : [ {
    "name" : "IT",
    "employees" : [ {
      "name" : "Alice",
      "age" : 30,
      "role" : "Developer"
    }, {
      "name" : "Bob",
      "age" : 28,
      "role" : "Designer"
    } ]
  }, {
    "name" : "HR",
    "employees" : [ {
      "name" : "Charlie",
      "age" : 32,
      "role" : "Manager"
    } ]
  } ]
}

以上就是Java实现JSON与XML相互转换的简明教程的详细内容,更多关于Java JSON与XML互转的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文