Google Gson使用

1. Gson简介

Gson是Google出品的一个JSON解析library,它可以将任意的Java对象转换为JSON string,也可以将JSON string转换为对应的Java对象。

官方介绍如下:

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.

2. maven依赖


    
    
      com.google.code.gson
      gson
      2.8.5
    

3. 数据准备

queryResultList>>类型数据:

[{
    fieldList = {
        author = [],
        booktype = []
    },
    author = 鲁迅,
    price = 60
},
{
    fieldList = {
        author = [],
        booktype = []
    },
    author = 鲁迅,
    price = 60
}]

4. 使用

public static void main(String[] args) {
        Gson gson = new Gson();
        Type tempType = new TypeToken>>().getType();
        
        // 序列化
//        String queryResultStr = gson.toJson(queryResult,tempType);
        String queryResultStr = gson.toJson(queryResult);

		// 反序列化
        List> queryResult2 = gson.fromJson(queryResultStr,tempType);
    }

你可能感兴趣的:(Google Gson使用)