详解XML,Object,Json转换与Xstream的使用

XML与对象之间的转换是应用中常见的操作之一。Java开发中最常用的方式是使用Java自带的JAXB库或第三方库Xstream来实现。

详解XML,Object,Json转换与Xstream的使用

XML与对象的相互转换

XML与对象之间的转换是应用中常见的操作之一。Java开发中最常用的方式是使用Java自带的JAXB库或第三方库Xstream来实现。

使用JAXB实现XML与对象的转换

JAXB是Java API for XML Binding(Java API的XML绑定)的简称,它可以将Java对象与XML相互转换。JAXB规范的实现一般由JDK自带,使用JAXB需要在pom.xml文件中添加以下依赖:

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.1</version>
</dependency>
<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-core</artifactId>
    <version>2.3.0.1</version>
</dependency>
<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-impl</artifactId>
    <version>2.3.0.1</version>
</dependency>

以下是示例代码:

将Java对象转换成XML格式
@XmlRootElement
public class Student {

    @XmlElement
    private String name;

    @XmlElement
    private int age;

    @XmlElement
    private List<String> courses;

    // 省略getter和setter方法

}
public class XmlUtil {

    public static String toXml(Object obj) throws JAXBException {
        JAXBContext ctx = JAXBContext.newInstance(obj.getClass());
        Marshaller marshaller = ctx.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        StringWriter sw = new StringWriter();
        marshaller.marshal(obj, sw);
        return sw.toString();
    }

}
public class Main {

    public static void main(String[] args) throws JAXBException {
        List<String> courses = new ArrayList<>();
        courses.add("Math");
        courses.add("English");
        Student student = new Student();
        student.setName("Tom");
        student.setAge(20);
        student.setCourses(courses);

        String xml = XmlUtil.toXml(student); 
        System.out.println(xml);
    }

}

输出结果:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<student>
    <name>Tom</name>
    <age>20</age>
    <courses>Math</courses>
    <courses>English</courses>
</student>
将XML格式转换成Java对象
@XmlRootElement
public class Student {

    @XmlElement
    private String name;

    @XmlElement
    private int age;

    @XmlElementWrapper(name="courses")
    @XmlElement(name="course")
    private List<String> courses;

    // 省略getter和setter方法

}
public class XmlUtil {

    @SuppressWarnings("unchecked")
    public static <T> T fromXml(String xml, Class<T> clazz) throws JAXBException {
        JAXBContext ctx = JAXBContext.newInstance(clazz);
        Unmarshaller unmarshaller = ctx.createUnmarshaller();
        StringReader sr = new StringReader(xml);
        return (T)unmarshaller.unmarshal(sr);
    }

}
public class Main {

    public static void main(String[] args) throws JAXBException {
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
                     "<student>\n" +
                     "    <name>Tom</name>\n" +
                     "    <age>20</age>\n" +
                     "    <courses>\n" +
                     "        <course>Math</course>\n" +
                     "        <course>English</course>\n" +
                     "    </courses>\n" +
                     "</student>";

        Student student = XmlUtil.fromXml(xml, Student.class);
        System.out.println(student.getName());
        System.out.println(student.getAge());
        System.out.println(student.getCourses());
    }

}

输出结果:

Tom
20
[Math, English]

使用Xstream实现XML与对象的转换

Xstream是一个Java API,它可以将Java对象与XML相互转换,使用Xstream需要在pom.xml文件中添加依赖:

<dependency>
    <groupId>com.thoughtworks.xstream</groupId>
    <artifactId>xstream</artifactId>
    <version>1.4.15</version>
</dependency>

以下是示例代码:

将Java对象转换成XML格式
public class Student {

    private String name;

    private int age;

    private List<String> courses;

    // 省略getter和setter方法

}
public class XmlUtil {

    public static String toXml(Object obj) {
        XStream xstream = new XStream();
        xstream.autodetectAnnotations(true);
        return xstream.toXML(obj);
    }

}
public class Main {

    public static void main(String[] args) {
        List<String> courses = new ArrayList<>();
        courses.add("Math");
        courses.add("English");
        Student student = new Student();
        student.setName("Tom");
        student.setAge(20);
        student.setCourses(courses);

        String xml = XmlUtil.toXml(student);
        System.out.println(xml);
    }

}

输出结果:

<com.example.demo.Student>
  <name>Tom</name>
  <age>20</age>
  <courses>
    <string>Math</string>
    <string>English</string>
  </courses>
</com.example.demo.Student>
将XML格式转换成Java对象
public class Student {

    private String name;

    private int age;

    @XStreamImplicit
    private List<String> courses;

    // 省略getter和setter方法

}
public class XmlUtil {

    @SuppressWarnings("unchecked")
    public static <T> T fromXml(String xml, Class<T> clazz) {
        XStream xstream = new XStream();
        xstream.autodetectAnnotations(true);
        xstream.alias(clazz.getSimpleName(), clazz);
        return (T)xstream.fromXML(xml);
    }

}
public class Main {

    public static void main(String[] args) {
        String xml = "<com.example.demo.Student>\n" +
                     "  <name>Tom</name>\n" +
                     "  <age>20</age>\n" +
                     "  <courses>\n" +
                     "    <string>Math</string>\n" +
                     "    <string>English</string>\n" +
                     "  </courses>\n" +
                     "</com.example.demo.Student>";

        Student student = XmlUtil.fromXml(xml, Student.class);
        System.out.println(student.getName());
        System.out.println(student.getAge());
        System.out.println(student.getCourses());
    }

}

输出结果:

Tom
20
[Math, English]

Java对象与JSON格式相互转换

Java对象与JSON之间的转换也是应用程序中经常要做的操作。Java开发中最常用的方式是使用JSON-lib库来实现。

使用JSON-lib实现Java对象转换成JSON格式

JSON-lib是一个Java的JSON工具包,它可以将Java对象转换成JSON格式数据。在pom.xml文件中添加依赖:

<dependency>
    <groupId>net.sf.json-lib</groupId>
    <artifactId>json-lib</artifactId>
    <version>2.4</version>
    <classifier>jdk15</classifier>
</dependency>

以下是示例代码:

public class Student {

    private String name;

    private int age;

    private List<String> courses;

    // 省略getter和setter方法

}
public class JsonUtil {

    public static String toJson(Object obj) {
        JSONObject jsonObject = JSONObject.fromObject(obj);
        return jsonObject.toString();
    }

}
public class Main {

    public static void main(String[] args) {
        List<String> courses = new ArrayList<>();
        courses.add("Math");
        courses.add("English");
        Student student = new Student();
        student.setName("Tom");
        student.setAge(20);
        student.setCourses(courses);

        String json = JsonUtil.toJson(student);
        System.out.println(json);
    }

}

输出结果:

{
    "courses": [
        "Math",
        "English"
    ],
    "age": 20,
    "name": "Tom"
}

使用JSON-lib实现JSON格式转换成Java对象

以下是示例代码:

public class Student {

    private String name;

    private int age;

    @SuppressWarnings("unchecked")
    private List<String> courses;

    // 省略getter和setter方法

}
public class JsonUtil {

    @SuppressWarnings("unchecked")
    public static <T> T fromJson(String json, Class<T> clazz) {
        JSONObject jsonObject = JSONObject.fromObject(json);
        return (T)JSONObject.toBean(jsonObject, clazz);
    }

}
public class Main {

    public static void main(String[] args) {
        String json = "{\n" +
                      "    \"courses\": [\n" +
                      "        \"Math\",\n" +
                      "        \"English\"\n" +
                      "    ],\n" +
                      "    \"age\": 20,\n" +
                      "    \"name\": \"Tom\"\n" +
                      "}";

        Student student = JsonUtil.fromJson(json, Student.class);
        System.out.println(student.getName());
        System.out.println(student.getAge());
        System.out.println(student.getCourses());
    }

}

输出结果:

Tom
20
[Math, English]

XML与JSON之间的转换

XML与JSON之间的转换也是应用程序中常见的操作之一。使用Xstream可以简单地实现XML转JSON和JSON转XML的操作。

以下是示例代码:

XML转JSON
public class Student {

    @XStreamAlias("Name")
    private String name;

    @XStreamAlias("Age")
    private int age;

    @XStreamImplicit(itemFieldName="Course")
    private List<String> courses;

    // 省略getter和setter方法

}
public class XmlJsonUtil {

    public static String xml2Json(String xml) {
        XStream xstream = new XStream(new JsonHierarchicalStreamDriver());
        xstream.registerConverter(new DateConverter("yyyy-MM-dd", new String[0]));
        xstream.processAnnotations(Student.class);
        Student student = (Student)xstream.fromXML(xml);
        return JSON.toJSONString(student);
    }

}
public class Main {

    public static void main(String[] args) {
        String xml = "<Student>\n" +
                     "  <Name>Tom</Name>\n" +
                     "  <Age>20</Age>\n" +
                     "  <Course>Math</Course>\n" +
                     "  <Course>English</Course>\n" +
                     "</Student>";

        String json = XmlJsonUtil.xml2Json(xml);
        System.out.println(json);
    }

}

输出结果:

{"Age":20,"Course":["Math","English"],"Name":"Tom"}
JSON转XML
public class Student {

    private String name;

    private int age;

    private List<String> courses;

    // 省略getter和setter方法

}
public class XmlJsonUtil {

    public static String json2Xml(String json) {
        Student student = JSON.parseObject(json, Student.class);
        XStream xstream = new XStream();
        xstream.autodetectAnnotations(true);
        return xstream.toXML(student);
    }

}
public class Main {

    public static void main(String[] args) {
        String json = "{\"name\":\"Tom\",\"age\":20,\"courses\":[\"Math\",\"English\"]}";

        String xml = XmlJsonUtil.json2Xml(json);
        System.out.println(xml);
    }

}

输出结果:

<Student>
  <name>Tom</name>
  <age>20</age>
  <courses>
    <string>Math</string>
    <string>English</string>
  </courses>
</Student>

Xstream的使用

在以上示例中,我们使用了Xstream来实现XML和JSON与Java对象之间的转换。Xstream可以自动将Java对象转换成相应的XML或JSON格式数据,也可以将XML或JSON格式数据转换成Java对象。

以下是示例代码:

将Java对象转换成XML或JSON格式
public class Student {

    private String name;

    private int age;

    private List<String> courses;

    // 省略getter和setter方法

}
public class XmlJsonUtil {

    public static String toXml(Object obj) {
        XStream xstream = new XStream();
        xstream.autodetectAnnotations(true);
        return xstream.toXML(obj);
    }

    public static String toJson(Object obj) {
        XStream xstream = new XStream(new JsonHierarchicalStreamDriver());
        xstream.useAttributeFor(String.class);
        xstream.autodetectAnnotations(true);
        return xstream.toXML(obj);
    }

}
public class Main {

    public static void main(String[] args) {
        List<String> courses = new ArrayList<>();
        courses.add("Math");
        courses.add("English");
        Student student = new Student();
        student.setName("Tom");
        student.setAge(20);
        student.setCourses(courses);

        String xml = XmlJsonUtil.toXml(student);
        String json = XmlJsonUtil.toJson(student);
        System.out.println(xml);
        System.out.println(json);
    }

}

输出结果:

<Student>
  <name>Tom</name>
  <age>20</age>
  <courses>
    <string>Math</string>
    <string>English</string>
  </courses>
</Student>
{"student":{"name":"Tom","age":20,"courses":{"string":["Math","English"]}}}
将XML或JSON格式转换成Java对象
public class XmlJsonUtil {

    public static <T> T fromXml(String xml, Class<T> clazz) {
        XStream xstream = new XStream();
        xstream.autodetectAnnotations(true);
        xstream.alias(clazz.getSimpleName(), clazz);
        return (T)xstream.fromXML(xml);
    }

    public static <T> T fromJson(String json, Class<T> clazz) {
        XStream xstream = new XStream(new JsonHierarchicalStreamDriver());
        xstream.useAttributeFor(String.class);
        xstream.autodetectAnnotations(true);
        xstream.alias(clazz.getSimpleName(), clazz);
        return (T)xstream.fromXML(json);
    }

}
public class Main {

    public static void main(String[] args) {
        String xml = "<Student>\n" +
                     "  <name>Tom</name>\n" +
                     "  <age>20</age>\n" +
                     "  <courses>\n" +
                     "    <string>Math</string>\n" +
                     "    <string>English</string>\n" +
                     "  </courses>\n" +
                     "</Student>";

        String json = "{\"student\":{\"name\":\"Tom\",\"age\":20,\"courses\":{\"string\":[\"Math\",\"English\"]}}}";

        Student student1 = XmlJsonUtil.fromXml(xml, Student.class);
        Student student2 = XmlJsonUtil.fromJson(json, Student.class);
        System.out.println(student1.getName());
        System.out.println(student1.getAge());
        System.out.println(student1.getCourses());
        System.out.println(student2.getName());
        System.out.println(student2.getAge());
        System.out.println(student2.getCourses());
    }

}

输出结果:

Tom
20
[Math, English]
Tom
20
[Math, English]

本文标题为:详解XML,Object,Json转换与Xstream的使用

基础教程推荐