更新于:2020-04-21

# Json 概述

wiki 描述

JSON 是一种轻量级的数据交换语言,JSON 数据格式与语言无关,对比于 XML 更小巧,以及浏览器的内建快速解析的支持,使得其更适用于网络数据传输领域

JSON 的工具类有很多,例如 JDK 自带的,Google 提供的 Gson,Jackson ,FastJson 等。

下面简单介绍几种常见的 JOSN 工具,Gson,Jackson 和 FastJson。

# Gson

# Introduce

版本:gson 2.8.6

Gson GitHub

Gson Guide

Gson API DOC

Gson 官方介绍如下

Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.

大意如下

Gson 是一个 java 类库,它支持 Java Object -> Json字符串 的转换,也支持 Json字符串 -> Java Object 的转换。

# 简单API使用

1、引入依赖 com.google.code.gson

2、测试对象

/** gson 测试对象 **/
    @Getter
    @Setter
    @Builder
    @ToString
    @AllArgsConstructor
    @NoArgsConstructor
    public static class GsonTestObject{
        private int age;
        private String name;
        private List<Hobby> hobbies;
        private LocalDateTime birthday;
    }
    @Getter
    @Setter
    @Builder
    @ToString
    @AllArgsConstructor
    @NoArgsConstructor
    public static class Hobby{
        private String name;
    }

3、测试 API

对象->json Gson#toJson

json -> 对象 Gson#fromJson

# 简单对象转换

/**
 * <p> Gson 简单 API 使用 </p>
 *
 * @Author 彳失口亍
 */
public class GsonSimpleApi {
    public static void main(String[] args) {
        // 单个对象
        GsonTestObject simpleObject = GsonTestObject.builder()
                .age(11)
                .birthday(LocalDateTime.now())
                .name("彳失口亍")
                .build();
        simpleTransfer(simpleObject);
    }

    /** 简单对象转换 **/
    public static void simpleTransfer(GsonTestObject simpleObject){
        Gson gson = new Gson();
        // object -> json
        String jsonStr = gson.toJson(simpleObject);
        System.out.println("[SimpleObject->Json] result: " + jsonStr);
        // json -> object
        GsonTestObject fromJson = gson.fromJson(jsonStr, GsonTestObject.class);
        System.out.println("[Json->SimpleObject] result: " + fromJson);
    }
}

# 复杂对象转换

/**
 * <p> Gson 简单 API 使用 </p>
 *
 * @Author 彳失口亍
 */
public class GsonSimpleApi {
    public static void main(String[] args) {
        // 多个对象
        List<GsonTestObject> complexObject = new ArrayList<>();
        IntStream.rangeClosed(1,30).forEach(loopTimes->{
            // hobby
            List<Hobby> hobbies = new ArrayList<>();
            for(int i = 0;i <= loopTimes;i++){
                Hobby build = Hobby.builder()
                        .name(i + "-hobby")
                        .build();
                hobbies.add(build);
            }
            GsonTestObject object = GsonTestObject.builder()
                    .age(loopTimes)
                    .birthday(LocalDateTime.now())
                    .name("彳失口亍")
                    .hobbies(hobbies)
                    .build();
            complexObject.add(object);
        });
        complexTransfer(complexObject);
    }

    /** 复杂对象转换 **/
    public static void complexTransfer(List<GsonTestObject> complexObject){
        Gson gson = new Gson();
        // object -> json
        String jsonStr = gson.toJson(complexObject);
        System.out.println("[ComplexObject->Json] result: " + jsonStr);
        // json -> object
        List<GsonTestObject> fromJson = gson.fromJson(jsonStr,
                new TypeToken<List<GsonTestObject>>(){}.getType());
        System.out.println("[Json->ComplexObject] result: " + fromJson);
    }
}

# jackson

# Introduce

jackson Github

Jackson 根据功能的不同划分了几个相对独立的模块。其核心模块如下

# jackson-core

官方介绍

This project contains core low-level incremental ("streaming") parser and generator abstractions used by Jackson Data Processor. It also includes the default implementation of handler types (parser, generator) that handle JSON format.

大意如下:

jackson-core 提供了 jackson 数据处理器使用的核心底层增量解析器和生成器抽象,它还提供了处理 JSON 格式的处理程序类型的默认实现。

通过如下介绍

This package is the base on which Jackson data-binding package builds on.

能够知道,jackson-corejackson-databind 的底层依赖。

# jackson-annotations

官方介绍

This project contains general purpose annotations for Jackson Data Processor, used on value and handler types. The only annotations not included are ones that require dependency to the Databind package. Note that only annotations themselves (and related value classes) are included, but no functionality that uses annotations.

大意如下

jackson-annotations 定了除 jackson-databind模块使用到的之外的注解,不过仅仅是注解的定义,并没有功能的实现。

# jackson-databind

官方介绍

This project contains the general-purpose data-binding functionality and tree-model for Jackson Data Processor. It builds on Streaming API (stream parser/generator) package, and uses Jackson Annotations for configuration.

大意如下

jackson-databind 提供了 Jackson数据处理器的通用数据绑定功能和树模型。它构建在流API(流解析器/生成器)包上,并使用Jackson注释进行配置。

官方文档还提到 jackson 对其他的格式的支持

While the original use case for Jackson was JSON data-binding, it can now be used for other data formats as well, as long as parser and generator implementations exist. Naming of classes uses word 'JSON' in many places even though there is no actual hard dependency to JSON format.

只要存在响应的解析器和生成器的实现,就能够支持其他的数据格式。例如支持 xml 数据格式的模块 jackson-dataformat-xml

# 简单 API 使用

1、引入依赖

  • jackson-databind 该模块包含了 jackson-corejackson-annotations 模块

  • jackson-module-parameter-namesjackson-datatype-jdk8jackson-datatype-jsr310 数据类型转化模块,如 Java8 日格式的支持

2、测试对象

/** jackson 测试对象 **/
    @Getter
    @Setter
    @Builder
    @ToString
    @AllArgsConstructor
    @NoArgsConstructor
    public static class JacksonTestObject {
        private int age;
        private String name;
        private List<Hobby> hobbies;
        private LocalDateTime birthday;
    }
    @Getter
    @Setter
    @Builder
    @ToString
    @AllArgsConstructor
    @NoArgsConstructor
    public static class Hobby{
        private String name;
    }

3、测试 API

object -> json : ObjectMapper#writeValueAsString

json -> object : ObjectMapper#readValue

# 简单对象转换

/**
 * <p> jackson 简单 API 使用 </p>
 *
 * @Author 彳失口亍
 */
public class JacksonSimpleJsonApi {
    public static void main(String[] args) throws JsonProcessingException {
        // 单个对象
        JacksonTestObject simpleObject = JacksonTestObject.builder()
                .age(11)
                .birthday(LocalDateTime.now())
                .name("彳失口亍")
                .build();
        simpleTransfer(simpleObject);
    }

    /** 简单对象转换 **/
    public static void simpleTransfer(JacksonTestObject simpleObject) throws JsonProcessingException {
        // findAndRegisterModules 自定注册包中模块,如 Java8 时间格式的支持
        ObjectMapper mapper = new ObjectMapper().findAndRegisterModules();
        // 美化输出
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        // object -> json
        String jsonStr = mapper.writeValueAsString(simpleObject);
        System.out.println("[SimpleObject->Json] result: " + jsonStr);

        // json -> object
        JacksonTestObject fromJson = mapper.readValue(jsonStr, JacksonTestObject.class);
        System.out.println("[Json->SimpleObject] result: " + fromJson);
    }
}

# 复杂对象转换

/**
 * <p> jackson 简单 API 使用 </p>
 *
 * @Author 彳失口亍
 */
public class JacksonSimpleJsonApi {
    public static void main(String[] args) throws JsonProcessingException {
        // 多个对象
        List<JacksonTestObject> complexObject = new ArrayList<>();
        IntStream.rangeClosed(1,30).forEach(loopTimes->{
            // hobby
            List<Hobby> hobbies = new ArrayList<>();
            for(int i = 0;i <= loopTimes;i++){
                Hobby build = Hobby.builder()
                        .name(i + "-hobby")
                        .build();
                hobbies.add(build);
            }
            JacksonTestObject object = JacksonTestObject.builder()
                    .age(loopTimes)
                    .birthday(LocalDateTime.now())
                    .name("彳失口亍")
                    .hobbies(hobbies)
                    .build();
            complexObject.add(object);
        });
        complexTransfer(complexObject);
    }

    /** 复杂对象转换 **/
    public static void complexTransfer(List<JacksonTestObject> complexObject) throws JsonProcessingException {
        // findAndRegisterModules 自定注册包中模块,如 Java8 时间格式的支持
        ObjectMapper mapper = new ObjectMapper().findAndRegisterModules();
        // 美化输出
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        // object -> json
        String jsonStr = mapper.writeValueAsString(complexObject);
        System.out.println("[SimpleObject->Json] result: " + jsonStr);

        // json -> object
        List<JacksonTestObject> fromJson = mapper.readValue(jsonStr, new TypeReference<List<JacksonTestObject>>(){});
        System.out.println("[Json->SimpleObject] result: " + fromJson);
    }
}

# 扩展:xml 数据格式

需要支持 xml 数据格式需要引入相关的扩展组件模块 jackson-dataformat-xml

jackson-dataformat-xml 官方介绍

This projects contains Jackson extension component for reading and writing XML encoded data.

大意如下:

jackson-dataformat-xml 模块是jackson扩展组件,提供了xml编码数据的读取和写入功能。

jackson-dataformat-xml 的使用格式和 json 格式的转化基本一致,区别在于 json转换使用的对象是 ObjectMapper ,而 XML 转换使用的是 XmlMapper

ObjectMapper 是 XmlMapper 父类

# FastJson

# Introduce

官方文档介绍

Fastjson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object.

大意如下

Fastjson 是一个 java 类库,它支持 Java Object -> Json字符串 的转换,也支持 Json字符串 -> Java Object 的转换。

# 简单 API 测试

入门案例文档

1、引入依赖

fastjson

2、测试对象

/** fastjson 测试对象 **/
    @Getter
    @Setter
    @Builder
    @ToString
    @AllArgsConstructor
    @NoArgsConstructor
    public static class FastJsonTestObject {
        private int age;
        private String name;
        private List<Hobby> hobbies;
        private LocalDateTime birthday;
    }
    @Getter
    @Setter
    @Builder
    @ToString
    @AllArgsConstructor
    @NoArgsConstructor
    public static class Hobby{
        private String name;
    }

# 简单对象

/**
 * <p> jackson 简单 API 使用 </p>
 *
 * @Author 彳失口亍
 */
public class FastjsonSimpleApi {
    public static void main(String[] args){
        // 单个对象
        FastJsonTestObject simpleObject = FastJsonTestObject.builder()
                .age(11)
                .birthday(LocalDateTime.now())
                .name("彳失口亍")
                .build();
        simpleTransfer(simpleObject);
    }

    /** 简单对象转换 **/
    public static void simpleTransfer(FastJsonTestObject simpleObject){
        // object -> json
        String jsonStr = JSONObject.toJSONString(simpleObject);
        System.out.println("[SimpleObject->Json] result: " + jsonStr);

        // json -> object
        FastJsonTestObject fromJson = JSONObject.parseObject(jsonStr,FastJsonTestObject.class);
        System.out.println("[Json->SimpleObject] result: " + fromJson);
    }
}

# 复杂对象

/**
 * <p> jackson 简单 API 使用 </p>
 *
 * @Author 彳失口亍
 */
public class FastjsonSimpleApi {
    public static void main(String[] args){
        // 多个对象
        List<FastJsonTestObject> complexObject = new ArrayList<>();
        IntStream.rangeClosed(1,30).forEach(loopTimes->{
            // hobby
            List<Hobby> hobbies = new ArrayList<>();
            for(int i = 0;i <= loopTimes;i++){
                Hobby build = Hobby.builder()
                        .name(i + "-hobby")
                        .build();
                hobbies.add(build);
            }
            FastJsonTestObject object = FastJsonTestObject.builder()
                    .age(loopTimes)
                    .birthday(LocalDateTime.now())
                    .name("彳失口亍")
                    .hobbies(hobbies)
                    .build();
            complexObject.add(object);
        });
        complexTransfer(complexObject);
    }

    /** 复杂对象转换 **/
    public static void complexTransfer(List<FastJsonTestObject> complexObject) {
        // object -> json
        String jsonStr = JSONObject.toJSONString(complexObject);
        System.out.println("[SimpleObject->Json] result: " + jsonStr);

        // json -> object
        List<FastJsonTestObject> fromJson = JSONArray.parseArray(jsonStr,FastJsonTestObject.class);
        System.out.println("[Json->SimpleObject] result: " + fromJson);
    }
}
精彩内容推送,请关注公众号!
最近更新时间: 4/22/2020, 7:23:53 PM