Gson轉換 — json資料轉換為Object實體公共方法

龍ing3發表於2017-05-23

Gson轉換 — json資料轉換為Object實體

最近在做遠端介面呼叫時,需要對資料進行加解密,因此返回的引數統一為以下json格式

{
    "code":0,
    "msg":"成功",
    "sign":"abcdefghijkl",
    "timestamp":1491897441000,
    "data":{}
}

首先,我們假設傳輸過程中的物件實體是

user.java

public class User {

    private int id;

    private String name;

    ...省略get set...
    
    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + "]";
    }

}

當返回的資料轉成物件時,可能存在三種情況:

1. User 物件
2. List<User> list 物件
3. Page page

Page.java

public class Page<T> {

    private int page;

    private int size;

    private int total;

    private List<T> data;

    ...省略 get set...
    
        @Override
    public String toString() {
        return "User [page=" + page + ", size=" + size + ", total=" + total + ", data=" + data + "]";
    }
    
}

因此返回data的json可能為以下三種:

1.物件實體的json json -> User

{
    "id":1,
    "name":"eric"
}

2.物件實體列表的json json -> List<User> list

[
    {
        "id":1,
        "name":"eric"
    },
    {
        "id":2,
        "name":"john"
    }
]

3.分頁的實體json json -> Page<User> page

{
    "page":1,
    "size":10,
    "total":2,
    "data":[
        {
            "id":1,
            "name":"eric"
        },
        {
            "id":2,
            "name":"john"
        }
    ]
}

因此我們需要寫一個公共類解決上述轉換問題

GsonUtils.java

public class GsonUtils {

    private GsonUtils() {

    }

    public static <T>T fromJson(String json,Class<T> type){
        Gson gson = new Gson();
        return gson.fromJson(json,type);

    }

    public static <T> List<T> listFromJson(String json){
        Gson gson = new Gson();
        return gson.fromJson(json, new TypeToken<List<T>>(){}.getType());
    }

}

測試:

public class Main {

    public static void main(String[] args) {

        String json1 = "{"id":1,"name":"eric"}";
        String json2 = "[{"id":1,"name":"eric"},{"id":2,"name":"john"}]";
        String json3 = "{"page":1,"size":10,"total":2,"data":[{"id":1,"name":"eric"},{"id":2,"name":"john"}]}";

        User user = GsonUtils.fromJson(json1, User.class);
        List<User> lists = GsonUtils.listFromJson(json2);
        Page<User> page = GsonUtils.fromJson(json3, Page.class);

        System.out.println("user:" + user);
        System.out.println("lists:" + lists);
        System.out.println("page:" + page);

    }

}

執行後的結果:

user:User [id=1, name=eric]
lists:[{id=1.0, name=eric}, {id=2.0, name=john}]
page:User [page=1, size=10, total=2, list=[{id=1.0, name=eric}, {id=2.0, name=john}]]

此時已經成功將三種格式的json轉化為Object,但是這裡有個問題如下:如果我們用一下方法獲取user,就會報錯,因為處理Java反射TypeToken泛型執行時型別擦除

User user = lists.get(0);
Exception in thread "main" java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to swun.test.entity.User
    at swun.test.Main.main(Main.java:27)

因此我們將方法listFromJson修改為

    public static <T> List<T> listFromJson(String json,Type type){
        Gson gson = new Gson();
        return gson.fromJson(json, type);
    }

在呼叫的時候,將具體的Type傳入

public class Main {

    public static void main(String[] args) {

        String json1 = "{"id":1,"name":"eric"}";
        String json2 = "[{"id":1,"name":"eric"},{"id":2,"name":"john"}]";
        String json3 = "{"page":1,"size":10,"total":2,"data":[{"id":1,"name":"eric"},{"id":2,"name":"john"}]}";

        User user = GsonUtils.fromJson(json1, User.class);
        List<User> lists = GsonUtils.listFromJson(json2,new TypeToken<List<User>>(){}.getType());
        Page<User> page = GsonUtils.fromJson(json3, Page.class);

        System.out.println("user:" + user);
        System.out.println("lists:" + lists);
        System.out.println("page:" + page);

        User user1 = lists.get(0);
        System.out.println("user1:" + user1);

    }

}

執行結果如下:

user:User [id=1, name=eric]
lists:[User [id=1, name=eric], User [id=2, name=john]]
page:User [page=1, size=10, total=2, data=[{id=1.0, name=eric}, {id=2.0, name=john}]]
user1:User [id=1, name=eric]

相關文章