欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

GSON 转换

程序员文章站 2022-06-15 13:47:42
...


import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;
import java.util.Date;

public class LongDateTypeAdapter extends TypeAdapter<Date> {
    @Override
    public void write(JsonWriter out, Date value) throws IOException {
        if (value == null) {
            out.nullValue();
        } else {
            out.value(value.getTime());
        }
    }

    @Override
    public Date read(JsonReader in) throws IOException {
        if (in.peek() == null) {
            return null;
        }
        String str = in. nextString();
        Date d  = new Date(Long.parseLong(str));
        return d;
    }
}

 

 

public class EntityGson <T>{
    public String type;
    public T data;

    public EntityGson(String type, T data) {
        this.type = type;
        this.data = data;
    }

    public EntityGson() {
    }

    public String  getGsonString()
    {
       
        Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new LongDateTypeAdapter()).create();
        String strRpt=  gson.toJson(this);
        return strRpt;
    }

   static public String getType(String msg)
    {
        JsonElement je = new JsonParser().parse(msg);
        String retype  = je.getAsJsonObject().get("type").getAsString();
        return retype;
    }


    static  public <T> T getData(String type, String msg)
    {
        Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new LongDateTypeAdapter()).create();




        switch(type)
        {
            case "RelayCtrl": {
                Type userType = new TypeToken<EntityGson<RelayCtrl>>() {
                }.getType();
                EntityGson<RelayCtrl> userResult = gson.fromJson(msg, userType);
                return  (T)userResult.data;
            }

            case "RptNode":{
                Type userType = new TypeToken<EntityGson<RptNode>>() {
                }.getType();
                EntityGson<RptNode> userResult = gson.fromJson(msg, userType);
                return  (T)userResult.data;
            }

            case "SetDomain":{
                Type userType = new TypeToken<EntityGson<SetDomain>>() {
                }.getType();
                EntityGson<SetDomain> userResult = gson.fromJson(msg, userType);
                return  (T)userResult.data;
            }
        }
        return null;
    }

}