com.unovo.frame.utils.gson.deserializer.ListJsonDeserializer.java Source code

Java tutorial

Introduction

Here is the source code for com.unovo.frame.utils.gson.deserializer.ListJsonDeserializer.java

Source

/*
 * Copyright (c) 2017 ?. All Rights Reserved.
 * Use of this source code is governed by a Shanghai Unovo Information Technology Co.,Ltd license
 * that can be found in the LICENSE file in the root of the web site.
 *
 *   http://www.unovo.com.cn
 *
 * An additional intellectual property rights grant can be found
 * in the file PATENTS.  All contributing project authors may
 * be found in the AUTHORS file in the root of the source tree.
 *
 */

package com.unovo.frame.utils.gson.deserializer;

import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by Aeatho on 2016/12/29 17:33
 *
 * Prject: unovo-guest-app
 * Description:
 * email: aeatho@gmail.com
 */
public class ListJsonDeserializer implements JsonDeserializer<List<?>> {
    @Override
    public List<?> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
            throws JsonParseException {
        if (json.isJsonArray()) {
            JsonArray array = json.getAsJsonArray();
            Type itemType = ((ParameterizedType) typeOfT).getActualTypeArguments()[0];
            List list = new ArrayList<>();
            for (int i = 0; i < array.size(); i++) {
                JsonElement element = array.get(i);
                Object item = context.deserialize(element, itemType);
                list.add(item);
            }
            return list;
        } else {
            //??List
            return Collections.EMPTY_LIST;
        }
    }
}