Google Gson使用

1484 ワード

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);
    }