package com.xinwei.util; import java.lang.reflect.Type; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; 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; public class JsonUtil{ // 支持转换的日期格式 public static final DateFormat[] ACCEPT_DATE_FORMATS = { new SimpleDateFormat("MM/dd/yyyy"), new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), new SimpleDateFormat("yyyy/MM/dd HH:mm:ss") }; /** * 将对象序列化为json字符串,只对有@expose注解的进行序列化 * @param obj * @return */ public static String toJsonWithExclusive(Object obj){ Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation() .registerTypeAdapter(Date.class, new MyDateSerializer()) .create(); String json = gson.toJson(obj); return json; } /** * 将对象序列化为json字符串,不区分注解 * @param obj * @return */ public static String toJson(Object obj){ Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new MyDateSerializer()) .create(); String json = gson.toJson(obj); return json; } public static String toJsonFilterEquals(Object obj){ Gson gson = new GsonBuilder().disableHtmlEscaping().create(); String json = gson.toJson(obj); return json; } /** * 将对象序列化为json字符串,不区分注解 * @param obj * @return */ public static String toJson0(Object obj){ String json = toJson(obj, Date.class, new MyTimestampSerializer()); return json; } /** * 将对象序列化为json字符串,不区分注解 * @param obj * @return */ @SuppressWarnings("rawtypes") public static String toJson(Object obj,Class clazz,JsonSerializer serializer){ Gson gson = new GsonBuilder().registerTypeAdapter(clazz, serializer) .create(); String json = gson.toJson(obj); return json; } /** * 将json字符串反序列化为对象,不区分注解 * @param jsonStr * @param classOfT * @return */ @SuppressWarnings("unchecked") public staticT fromJson(String jsonStr,Type type){ Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new MyDateDeserializer()) .create(); return (T)gson.fromJson(jsonStr, type); } /** * 将json字符串反序列化为对象,区分注解 * @param jsonStr * @param classOfT * @return */ @SuppressWarnings("unchecked") public static T fromJsonWithExclusive(String jsonStr,Type type){ Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation() .registerTypeAdapter(Date.class, new MyDateDeserializer()) .create(); return (T)gson.fromJson(jsonStr, type); } @SuppressWarnings("rawtypes") public static Map fromJson(String jsonStr){ Type type = new TypeToken