Gson转JSON字符串时候, 将时间转成Long型

有些特定需求, 比如说搜索引擎, 很多人都要求时间必须是时间戳. 所以, 我们把时间转成最原始的Long型. Gson默认的是不支持的, 需要手动处理一下.

import java.lang.reflect.Type;  
import java.util.Date;

import com.google.gson.JsonDeserializationContext;  
import com.google.gson.JsonDeserializer;  
import com.google.gson.JsonElement;  
import com.google.gson.JsonParseException;

/**
 * Created with antnest-platform
 * User: chenyuan
 * Date: 12/22/14
 * Time: 4:39 PM
 */
public class DateDeserializer implements JsonDeserializer<java.util.Date> {

    public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        return new java.util.Date(json.getAsJsonPrimitive().getAsLong());
    }
}
import com.google.gson.JsonElement;

import java.lang.reflect.Type;  
import java.util.Date;

import com.google.gson.JsonPrimitive;  
import com.google.gson.JsonSerializationContext;  
import com.google.gson.JsonSerializer;

/**
 * Created with antnest-platform
 * User: chenyuan
 * Date: 12/22/14
 * Time: 4:38 PM
 */
public class DateSerializer implements JsonSerializer<Date> {  
    public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
        return new JsonPrimitive(src.getTime());
    }
}
import com.google.gson.Gson;  
import com.google.gson.GsonBuilder;

import java.text.DateFormat;

/**
 * Created with antnest-platform
 * User: chenyuan
 * Date: 12/22/14
 * Time: 4:33 PM
 */
public class GsonBuilderUtil {

    public static Gson create() {
        GsonBuilder gb = new GsonBuilder();
        gb.registerTypeAdapter(java.util.Date.class, new DateSerializer()).setDateFormat(DateFormat.LONG);
        gb.registerTypeAdapter(java.util.Date.class, new DateDeserializer()).setDateFormat(DateFormat.LONG);
        Gson gson = gb.create();
        return gson;
    }
}

最后, 我们在new Gson的时候, 我们 Gson gson = GsonBuilderUtil.create(); 就可以了.