toJson 时间格式化

来源:互联网 发布:工业设计主流软件 编辑:程序博客网 时间:2024/06/12 22:55
import java.lang.reflect.Type;import java.text.DateFormat;import java.util.Date;import com.google.gson.Gson;import com.google.gson.GsonBuilder;import com.google.gson.JsonDeserializationContext;import com.google.gson.JsonDeserializer;import com.google.gson.JsonElement;import com.google.gson.JsonParseException;import com.google.gson.JsonPrimitive;import com.google.gson.JsonSerializationContext;import com.google.gson.JsonSerializer;import com.google.gson.reflect.TypeToken;/** * Json转换工具 *                        * @Filename: JsonUtil.java * @Version: 1.0 * */public final class JsonUtil {    private static org.apache.log4j.Logger log = org.apache.log4j.LogManager        .getLogger(JsonUtil.class);    /**     * 将JSON字符串反序列化为Java对象。     * @param json JSON字符串     * @return     * <li>json字符串为空时返回null;     * <li>json字符串为无效JSON格式时,会记录日志,返回null;     */    public static final <T> T fromJson(String json) {        if (StringUtil.isEmpty(json))            return null;        try {            Type type = new TypeToken<T>() {            }.getType();            Gson gson = new Gson();            return gson.fromJson(json, type);        } catch (Exception e) {            log.warn("Invalidate json format:" + json, e);            return null;        }    }    /**     * 将Java对象序列化成JSON字符串。     * @param obj     * @return     */    public static final String toJson(Object obj) {        if (obj == null)            return null;        try {            GsonBuilder gb = new GsonBuilder();            gb.setDateFormat("yyyy-MM-dd HH:mm:ss");            return gb.create().toJson(obj);        } catch (Exception e) {            log.warn("Can not serialize object to json", e);            return null;        }    }        /**     * 格式时间成毫秒值     * @param obj     * @return     */    public static final String toFormatJson(Object obj) {        if (obj == null)            return null;        try {            GsonBuilder gb = new GsonBuilder();            gb.registerTypeAdapter(java.util.Date.class, new DateDeserializer()).setDateFormat(DateFormat.LONG);            gb.registerTypeAdapter(java.util.Date.class, new DateSerializer()).setDateFormat(DateFormat.LONG);            return gb.create().toJson(obj);        } catch (Exception e) {            log.warn("Can not serialize object to json", e);            return null;        }    }        public static 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());        }    }        public static class DateSerializer implements JsonSerializer<Date> {        public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {            return new JsonPrimitive(src.getTime());        }    }}


0 0
原创粉丝点击