您的位置:首页 > Web前端 > JavaScript

toJson 时间格式化

2016-03-30 17:39 477 查看
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());
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: