XStream User Guide: JSON – XStream用户指南 JSON

最后修改: 2016年 4月 11日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

This is the third article in a series about XStream. If you want to learn about its basic use in converting Java objects to XML and vice versa, please refer to the previous articles.

这是关于XStream系列的第三篇文章。如果您想了解它在将Java对象转换为XML反之亦然的基本用途,请参考之前的文章。

Beyond its XML-handling capabilities, XStream can also convert Java objects to and from JSON. In this tutorial, we will learn about these features.

除了XML处理能力外,XStream还可以将Java对象转换成JSON。在本教程中,我们将学习这些功能。

2. Prerequisites

2.先决条件

Before reading this tutorial, please go through the first article in this series, in which we explain the basics of the library.

在阅读本教程之前,请先阅读本系列的第一篇文章中我们解释了该库的基础知识。

3. Dependencies

3.依赖性

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

4. JSON Drivers

4.JSON驱动

In the previous articles, we learned how to set up an XStream instance and to select an XML driver. Similarly, there are two drivers available to convert objects to and from JSON: JsonHierarchicalStreamDriver and JettisonMappedXmlDriver.

在前面的文章中,我们学习了如何设置一个XStream实例和选择一个XML驱动。类似地,有两个驱动程序可用于将对象转换为JSON或从JSON中转换:JsonHierarchicalStreamDriverJettisonMappedXmlDriver

4.1. JsonHierarchicalStreamDriver

4.1.JsonHierarchicalStreamDriver

This driver class can serialize objects to JSON, but is not capable of deserializing back to objects. It does not require any extra dependencies, and its driver class is self-contained.

这个驱动类可以将对象序列化为JSON,但不能够反序列化为对象。它不需要任何额外的依赖,其驱动类是自成一体的。

4.2. JettisonMappedXmlDriver

4.2.JettisonMappedXmlDriver

This driver class is capable of converting JSON to and from objects. Using this driver class, we need to add an extra dependency for jettison.

这个驱动类能够将JSON转换为对象或从对象转换。使用这个驱动类,我们需要为jettison.添加一个额外的依赖。

<dependency>
    <groupId>org.codehaus.jettison</groupId>
    <artifactId>jettison</artifactId>
    <version>1.4.1</version>
</dependency>

5. Serializing an Object to JSON

5.将一个对象序列化为JSON

Let’s create a Customer class:

让我们创建一个Customer类。

public class Customer {

    private String firstName;
    private String lastName;
    private Date dob;
    private String age;
    private List<ContactDetails> contactDetailsList;
       
    // getters and setters
}

Note that we have (perhaps unexpectedly) created age as a String. We will explain this choice later.

请注意,我们已经(也许是出乎意料地)将年龄创建为字符串。我们将在后面解释这一选择。

5.1. Using JsonHierarchicalStreamDriver

5.1.使用JsonHierarchicalStreamDriver

We will pass a JsonHierarchicalStreamDriver to create an XStream instance.

我们将传递一个JsonHierarchicalStreamDriver来创建一个XStream实例。

xstream = new XStream(new JsonHierarchicalStreamDriver());
dataJson = xstream.toXML(customer);

This generates the following JSON:

这就产生了以下的JSON。

{
  "com.baeldung.pojo.Customer": {
    "firstName": "John",
    "lastName": "Doe",
    "dob": "1986-02-14 16:22:18.186 UTC",
    "age": "30",
    "contactDetailsList": [
      {
        "mobile": "6673543265",
        "landline": "0124-2460311"
      },
      {
        "mobile": "4676543565",
        "landline": "0120-223312"
      }
    ]
  }
}

5.2. JettisonMappedXmlDriver Implementation

5.2.JettisonMappedXmlDriver 实现

We will pass a JettisonMappedXmlDriver class to create an instance.

我们将传递一个JettisonMappedXmlDriver类来创建一个实例。

xstream = new XStream(new JettisonMappedXmlDriver());
dataJson = xstream.toXML(customer);

This generates the following JSON:

这就产生了以下的JSON。

{
  "com.baeldung.pojo.Customer": {
    "firstName": "John",
    "lastName": "Doe",
    "dob": "1986-02-14 16:25:50.745 UTC",
    "age": 30,
    "contactDetailsList": [
      {
        "com.baeldung.pojo.ContactDetails": [
          {
            "mobile": 6673543265,
            "landline": "0124-2460311"
          },
          {
            "mobile": 4676543565,
            "landline": "0120-223312"
          }
        ]
      }
    ]
  }
}

5.3. Analysis

5.3.分析

Based on the output from the two drivers, we can clearly see that there are some slight differences in the generated JSON. For example, JettisonMappedXmlDriver omits the double quotes for numeric values despite the data type being java.lang.String:

根据这两个驱动程序的输出,我们可以清楚地看到,在生成的JSON中存在一些轻微的差异。例如,JettisonMappedXmlDriver省略了数字值的双引号,尽管数据类型是java.lang.String

"mobile": 4676543565,
"age": 30,

JsonHierarchicalStreamDriver, on the other hand, retains the double quotes.

JsonHierarchicalStreamDriver,另一方面,保留了双引号。

6. Deserializing JSON to an Object

6.将JSON反序列化为一个对象

Let’s take the following JSON to convert it back to a Customer object:

让我们把下面的JSON转换为一个Customer 对象。

{
  "customer": {
    "firstName": "John",
    "lastName": "Doe",
    "dob": "1986-02-14 16:41:01.987 UTC",
    "age": 30,
    "contactDetailsList": [
      {
        "com.baeldung.pojo.ContactDetails": [
          {
            "mobile": 6673543265,
            "landline": "0124-2460311"
          },
          {
            "mobile": 4676543565,
            "landline": "0120-223312"
          }
        ]
      }
    ]
  }
}

Recall that only one of the drivers (JettisonMappedXMLDriver) can deserialize JSON. Attempting to use JsonHierarchicalStreamDriver for this purpose will result in an UnsupportedOperationException.

回顾一下,只有其中一个驱动(JettisonMappedXMLDriver)可以反序列化JSON。试图使用JsonHierarchicalStreamDriver来实现这一目的将导致UnsupportedOperationException

Using the Jettison driver, we can deserialize the Customer object:

使用Jettison驱动,我们可以反序列化Customer对象。

customer = (Customer) xstream.fromXML(dataJson);

7. Conclusion

7.结论

In this article we have covered the JSON handling capabilities XStream, converting objects to and from JSON. We also looked at how we can tweak our JSON output, making it shorter, simpler and more readable.

在这篇文章中,我们已经涵盖了JSON处理能力XStream,将对象转换为JSON或从JSON转换。我们还研究了如何调整我们的JSON输出,使其更短、更简单、更易读。

As with XStream’s XML processing, there are other ways we can further customize the way JSON is serialized by configuring the instance, using either annotations or programmatic configuration. For more details and examples, please refer to the first article in this series.

与 XStream 的 XML 处理一样,我们还可以通过配置实例,使用注释或编程配置,进一步定制 JSON 的序列化方式。有关更多细节和示例,请参考本系列的第一篇文章

The complete source code with examples can be downloaded from the linked GitHub repository.

带有示例的完整源代码可以从链接的GitHub存储库下载。