Gson配套工具类

JsonUtils.java

import android.util.Log;

import com.example.win.newintern3.Base.entity.ServiceEntity;
import com.example.win.newintern3.Base.ServiceListEntity;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by TAO_SX on 2016/6/28/028.
 */
public class JsonUtils {
    public static <T> T getPerson(String jsonString, Class<T> cls) {
        T t = null;

        try {
//            Gson gson = new Gson();
            Gson gson  = new GsonBuilder().registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory()).create();
            t = gson.fromJson(jsonString, cls);
        } catch (Exception e) {
            Log.e("json_error:",e.toString());
        }

        return t;
    }

    public static <T> ServiceListEntity<T> getServiceListEntity(String jsonString, Class<T> cls) {
        ServiceListEntity<T> listEntity = new ServiceListEntity<T>();

        try {

            JsonObject jsonObjects = new Gson().fromJson(jsonString, JsonObject.class);
            String code = jsonObjects.get("code").getAsString();
            jsonObjects.get("list").getAsJsonArray();

            List<T> arrayList = new ArrayList<T>();
            for (JsonElement jsonObject : jsonObjects.get("list").getAsJsonArray())
            {
                arrayList.add(new Gson().fromJson(jsonObject, cls));
            }
            listEntity.setList(arrayList);
            listEntity.setCode(code);
        } catch (Exception e) {
            Log.e("json_error:",e.toString());
        }

        return listEntity;
    }

    public static <T> ServiceEntity<T> getServiceEntity(String jsonString, Class<T> cls) {
        ServiceEntity<T> entity = new ServiceEntity<T>();

        try {

            JsonObject jsonObjects = new Gson().fromJson(jsonString, JsonObject.class);
            String code = jsonObjects.get("code").getAsString();            ;
            T info = new Gson().fromJson(jsonObjects.get("entity").getAsJsonObject(), cls);

            entity.setEntity(info);
            entity.setCode(code);
        } catch (Exception e) {
            Log.e("json_error:",e.toString());
        }

        return entity;
    }

    public static <T> ArrayList<T> getEntityArrayList(String jsonString, Class<T> cls){
        Type type = new TypeToken<ArrayList<JsonObject>>() {}.getType();
        ArrayList<JsonObject> jsonObjects = new Gson().fromJson(jsonString, type);

        ArrayList<T> arrayList = new ArrayList<>();
        for (JsonObject jsonObject : jsonObjects)
        {
            arrayList.add(new Gson().fromJson(jsonObject, cls));
        }
        return arrayList;
    }
//    public static String  toJson( Class<T>  cls,Class<T>  cls2) {
//        String t = null;
//
//        try {
////            Gson gson = new Gson();
//            Gson gson  = new GsonBuilder().registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory()).create();
//            t = gson.toJson(cls);
//        } catch (Exception e) {
//            Log.e("json_error:",e.toString());
//        }
//
//        return t;
//    }
//
   //处理null值
    public static class NullStringToEmptyAdapterFactory<T> implements TypeAdapterFactory {
        @SuppressWarnings("unchecked")
        public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
            Class<T> rawType = (Class<T>) type.getRawType();
            if (rawType != String.class) {
                return null;
            }
            return (TypeAdapter<T>) new StringNullAdapter();
        }
    }

    public static class StringNullAdapter extends TypeAdapter<String> {
        @Override
        public String read(JsonReader reader) throws IOException {
            // TODO Auto-generated method stub
            if (reader.peek() == JsonToken.NULL) {
                reader.nextNull();
                return "";
            }
            return reader.nextString();
        }
        @Override
        public void write(JsonWriter writer, String value) throws IOException {
            // TODO Auto-generated method stub
            if (value == null) {
                writer.nullValue();
                return;
            }
            writer.value(value);
        }
    }
}

ServiceEntity.java
(可根据实际需求改写)

package com.example.win.newintern3.Base.entity;
/**
 * Created by win on 2017/8/25.
 */

public class ServiceEntity<T> {
//    CompanyPracticePost

    private T entity;

    private String code;

    public ServiceEntity() {

    }

    public ServiceEntity(T entity, String code) {
        this.entity = entity;
        this.code = code;
    }

    public T getEntity() {
        return entity;
    }

    public void setEntity(T entity) {
        this.entity = entity;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    @Override
    public String toString() {
        return "ServiceEntity{" +
                "entity=" + entity +
                ", code='" + code + '\'' +
                '}';
    }
}

ServiceListEntity.java

import java.util.List;

/**
 * Created by win on 2017/8/25.
 */

public class ServiceListEntity<T> {
//    CompanyPracticePost

    private List<T> list;

    private String code;

    public ServiceListEntity() {

    }

    public ServiceListEntity(List<T> list, String code) {
        this.list = list;
        this.code = code;
    }

    public List<T> getList() {
        return list;
    }

    public void setList(List<T> list) {
        this.list = list;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    @Override
    public String toString() {
        return "ServiceListEntity{" +
                "list=" + list +
                ", code='" + code + '\'' +
                '}';
    }
}

调用:

1.  ServiceEntity<UserLoginMainEntity> Entity = JsonUtils.getServiceEntity(result, UserLoginMainEntity.class);
                    if (Entity.getCode().equals("200")) {
                    UserLoginMainEntity entity = Entity.getEntity();
                    }
2.  ServiceListEntity<UserLoginMainEntity> Entity = JsonUtils.getServiceListEntity(result, UserLoginMainEntity.class);
                    if (Entity.getCode().equals("200")) {
                    List<UserLoginMainEntity> list= Entity.getList();
                    }
3.  UserLoginMainEntity Entity = JsonUtils.getPerson(result, UserLoginMainEntity.class);

猜你喜欢

转载自blog.csdn.net/grandaunt/article/details/78434913
今日推荐