admin
2021-02-06 d1f26741bddf6f512d62c0100d42c52be8d37e76
utils/src/main/java/org/yeshi/utils/JsonUtil.java
@@ -1,217 +1,283 @@
package org.yeshi.utils;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import com.google.gson.ExclusionStrategy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import net.sf.json.JSONObject;
public class JsonUtil {
   public static String loadTrueResult(Object result) {
      JSONObject object = new JSONObject();
      object.put("code", 0);
      object.put("data", result);
      return object.toString();
   }
   public static String loadFalseResult(String error) {
      JSONObject object = new JSONObject();
      object.put("code", 1);
      object.put("msg", error);
      return object.toString();
   }
   public static String loadTrueResult(int code, Object result) {
      JSONObject object = new JSONObject();
      object.put("code", code);
      object.put("data", result);
      System.out.println(object.toString());
      return object.toString();
   }
   public static JSONObject loadTrue(int code, Object data, String msg) {
      JSONObject object = new JSONObject();
      object.put("code", code);
      object.put("data", data);
      object.put("msg", msg);
      System.out.println(object.toString());
      return object;
   }
   public static String loadJSONP(String callback, String data) {
      return callback + "(" + data + ")";
   }
   public static String loadFalseResult(int code, String error) {
      JSONObject object = new JSONObject();
      object.put("code", code);
      object.put("msg", error);
      return object.toString();
   }
   // 返回方式
   public static void printMode(PrintWriter out, String callback, String JsonData) {
      if (StringUtil.isNullOrEmpty(callback)) {
         out.print(JsonData);
      } else {
         out.print(JsonUtil.loadJSONP(callback, JsonData));
      }
   }
   public static JSONObject getJSONObject(Object obj) {
      Gson gson = new GsonBuilder().enableComplexMapKeySerialization().excludeFieldsWithoutExposeAnnotation()
            .setDateFormat(DateFormat.LONG).setPrettyPrinting().setVersion(1.0).create();
      return JSONObject.fromObject(gson.toJson(obj));
   }
   public static Gson getGson() {
      Gson gson = new GsonBuilder().enableComplexMapKeySerialization().excludeFieldsWithoutExposeAnnotation()
            .setDateFormat(DateFormat.LONG).setPrettyPrinting().setVersion(1.0).create();
      return gson;
   }
   public static Gson getSimpleGson() {
      return new GsonBuilder().create();
   }
   public static Gson getSimpleGsonWithDate() {
      GsonBuilder gb = new GsonBuilder();
      gb.registerTypeAdapter(java.util.Date.class, new JsonSerializer<Date>() {
         public JsonElement serialize(Date arg0, Type arg1, JsonSerializationContext arg2) {
            return new JsonPrimitive(arg0.getTime());
         }
      }).setDateFormat(DateFormat.LONG);
      Gson gson = gb.create();
      return gson;
   }
   public static Gson getSimpleGsonWithDateAndSerialization() {
      GsonBuilder gb = new GsonBuilder();
      gb.registerTypeAdapter(java.util.Date.class, new JsonSerializer<Date>() {
         public JsonElement serialize(Date arg0, Type arg1, JsonSerializationContext arg2) {
            return new JsonPrimitive(arg0.getTime());
         }
      }).setDateFormat(DateFormat.LONG);
      gb.excludeFieldsWithoutExposeAnnotation();
      Gson gson = gb.create();
      return gson;
   }
   public static Map<String, String> parseData(String data) {
      GsonBuilder gb = new GsonBuilder();
      Gson g = gb.create();
      Map<String, String> map = g.fromJson(data, new TypeToken<Map<String, String>>() {
      }.getType());
      return map;
   }
   // 将BigDecimal转为字符串
   public static GsonBuilder getConvertBigDecimalToStringBuilder(GsonBuilder builder) {
      return builder.registerTypeAdapter(BigDecimal.class, new JsonSerializer<BigDecimal>() {
         @Override
         public JsonElement serialize(BigDecimal value, Type theType, JsonSerializationContext context) {
            if (value == null) {
               return new JsonPrimitive("");
            } else {
               return new JsonPrimitive(value.toString());
            }
         }
      });
   }
   /**
    * 获取客户端接口常用的gson
    *
    * @return
    */
   public static Gson getApiCommonGson() {
      GsonBuilder gsonBuilder = getConvertBigDecimalToStringSubZeroBuilder(new GsonBuilder());
      gsonBuilder.excludeFieldsWithoutExposeAnnotation();
      return gsonBuilder.create();
   }
   public static GsonBuilder getConvertBigDecimalToStringSubZeroBuilder(GsonBuilder builder) {
      return builder.registerTypeAdapter(BigDecimal.class, new JsonSerializer<BigDecimal>() {
         @Override
         public JsonElement serialize(BigDecimal value, Type theType, JsonSerializationContext context) {
            if (value == null) {
               return new JsonPrimitive("");
            } else {
               return new JsonPrimitive(BigDecimalUtil.getWithNoZera(value).toString());
            }
         }
      });
   }
   // 将日期转为几天前这种形式
   public static GsonBuilder getConvertDateToShortNameBuilder(GsonBuilder builder) {
      return builder.registerTypeAdapter(Date.class, new TypeAdapter<Date>() {
         @Override
         public void write(JsonWriter out, Date value) throws IOException {
            String desc = "";
            if (value != null) {
               // 判断是否是同一天
               long old = value.getTime();
               long now = System.currentTimeMillis();
               long oldDay = old / (1000 * 60 * 60 * 24L);
               long nowDay = now / (1000 * 60 * 60 * 24L);
               if (oldDay == nowDay) {// 同一天
                  long cha = now - old;
                  if (cha < 1000 * 60 * 2L)
                     desc = "刚刚";
                  else if (cha < 1000 * 60 * 60L)
                     desc = (cha / (1000 * 60)) + "分钟前";
                  else
                     desc = (cha / (1000 * 60 * 60)) + "小时前";
               } else if (nowDay - oldDay == 1) {
                  desc = "昨天";
               } else {
                  desc = (nowDay - oldDay) + "天前";
               }
               out.value(desc);
            }
         }
         @Override
         public Date read(JsonReader in) throws IOException {
            return new Date();
         }
      });
   }
   public static Map<String, Object> parseData(JSONObject data) {
      Map<String, Object> map = new HashMap<String, Object>();
      Set<String> keySet = data.keySet();
      for (String key : keySet) {
         map.put(key, data.get(key));
      }
      return map;
   }
}
package org.yeshi.utils;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class JsonUtil {
   static Gson baseGson = new Gson();
   public static String loadTrueResult(Object result) {
      JSONObject object = new JSONObject();
      object.put("code", 0);
      object.put("data", result);
      return object.toString();
   }
   public static String loadFalseResult(String error) {
      JSONObject object = new JSONObject();
      object.put("code", 1);
      object.put("msg", error);
      return object.toString();
   }
   public static String loadTrueResult(int code, Object result) {
      JSONObject object = new JSONObject();
      object.put("code", code);
      object.put("data", result);
      System.out.println(object.toString());
      return object.toString();
   }
   public static JSONObject loadTrue(int code, Object data, String msg) {
      JSONObject object = new JSONObject();
      object.put("code", code);
      object.put("data", data);
      object.put("msg", msg);
      System.out.println(object.toString());
      return object;
   }
   public static String loadJSONP(String callback, String data) {
      if (StringUtil.isNullOrEmpty(callback))
         return data;
      else
         return callback + "(" + data + ")";
   }
   public static String loadFalseResult(int code, String error) {
      JSONObject object = new JSONObject();
      object.put("code", code);
      object.put("msg", error);
      return object.toString();
   }
   // 返回方式
   public static void printMode(PrintWriter out, String callback, String JsonData) {
      if (StringUtil.isNullOrEmpty(callback)) {
         out.print(JsonData);
      } else {
         out.print(JsonUtil.loadJSONP(callback, JsonData));
      }
   }
   public static JSONObject getJSONObject(Object obj) {
      Gson gson = new GsonBuilder().enableComplexMapKeySerialization().excludeFieldsWithoutExposeAnnotation()
            .setDateFormat(DateFormat.LONG).setPrettyPrinting().setVersion(1.0).create();
      return JSONObject.fromObject(gson.toJson(obj));
   }
   public static Gson getGson() {
      Gson gson = new GsonBuilder().enableComplexMapKeySerialization().excludeFieldsWithoutExposeAnnotation()
            .setDateFormat(DateFormat.LONG).setPrettyPrinting().setVersion(1.0).create();
      return gson;
   }
   public static Gson getSimpleGson() {
      return new GsonBuilder().create();
   }
   public static Gson getSimpleGsonWithDate() {
      GsonBuilder gb = new GsonBuilder();
      gb.registerTypeAdapter(java.util.Date.class, new JsonSerializer<Date>() {
         public JsonElement serialize(Date arg0, Type arg1, JsonSerializationContext arg2) {
            return new JsonPrimitive(arg0.getTime());
         }
      }).setDateFormat(DateFormat.LONG);
      Gson gson = gb.create();
      return gson;
   }
   public static Gson getSimpleGsonWithDateAndSerialization() {
      GsonBuilder gb = new GsonBuilder();
      gb.registerTypeAdapter(java.util.Date.class, new JsonSerializer<Date>() {
         public JsonElement serialize(Date arg0, Type arg1, JsonSerializationContext arg2) {
            return new JsonPrimitive(arg0.getTime());
         }
      }).setDateFormat(DateFormat.LONG);
      gb.excludeFieldsWithoutExposeAnnotation();
      Gson gson = gb.create();
      return gson;
   }
   public static Map<String, String> parseData(String data) {
      GsonBuilder gb = new GsonBuilder();
      Gson g = gb.create();
      Map<String, String> map = g.fromJson(data, new TypeToken<Map<String, String>>() {
      }.getType());
      return map;
   }
   // 将BigDecimal转为字符串
   public static GsonBuilder getConvertBigDecimalToStringBuilder(GsonBuilder builder) {
      return builder.registerTypeAdapter(BigDecimal.class, new JsonSerializer<BigDecimal>() {
         @Override
         public JsonElement serialize(BigDecimal value, Type theType, JsonSerializationContext context) {
            if (value == null) {
               return new JsonPrimitive("");
            } else {
               return new JsonPrimitive(value.toString());
            }
         }
      });
   }
   /**
    * 获取客户端接口常用的gson
    *
    * @return
    */
   public static Gson getApiCommonGson() {
      GsonBuilder gsonBuilder = getConvertBigDecimalToStringSubZeroBuilder(new GsonBuilder());
      gsonBuilder.excludeFieldsWithoutExposeAnnotation();
      return gsonBuilder.create();
   }
   public static GsonBuilder getConvertBigDecimalToStringSubZeroBuilder(GsonBuilder builder) {
      return builder.registerTypeAdapter(BigDecimal.class, new JsonSerializer<BigDecimal>() {
         @Override
         public JsonElement serialize(BigDecimal value, Type theType, JsonSerializationContext context) {
            if (value == null) {
               return new JsonPrimitive("");
            } else {
               return new JsonPrimitive(BigDecimalUtil.getWithNoZera(value).toString());
            }
         }
      });
   }
   // 将日期转为几天前这种形式
   public static GsonBuilder getConvertDateToShortNameBuilder(GsonBuilder builder) {
      return builder.registerTypeAdapter(Date.class, new TypeAdapter<Date>() {
         @Override
         public void write(JsonWriter out, Date value) throws IOException {
            String desc = "";
            if (value != null) {
               // 判断是否是同一天
               long old = value.getTime();
               long now = System.currentTimeMillis();
               long oldDay = old / (1000 * 60 * 60 * 24L);
               long nowDay = now / (1000 * 60 * 60 * 24L);
               if (oldDay == nowDay) {// 同一天
                  long cha = now - old;
                  if (cha < 1000 * 60 * 2L)
                     desc = "刚刚";
                  else if (cha < 1000 * 60 * 60L)
                     desc = (cha / (1000 * 60)) + "分钟前";
                  else
                     desc = (cha / (1000 * 60 * 60)) + "小时前";
               } else if (nowDay - oldDay == 1) {
                  desc = "昨天";
               } else {
                  desc = (nowDay - oldDay) + "天前";
               }
               out.value(desc);
            } else
               out.value("");
         }
         @Override
         public Date read(JsonReader in) throws IOException {
            return new Date();
         }
      });
   }
   public static Map<String, Object> parseData(JSONObject data) {
      Map<String, Object> map = new HashMap<String, Object>();
      Set<String> keySet = data.keySet();
      for (String key : keySet) {
         map.put(key, data.get(key));
      }
      return map;
   }
   /**
    * 将对象转换成json字符串。
    * <p>
    * Title: pojoToJson
    * </p>
    * <p>
    * Description:
    * </p>
    *
    * @param data
    * @return
    */
   public static String objectToJson(Object data) {
      String string = baseGson.toJson(data);
      return string;
   }
   /**
    * 将json结果集转化为对象
    *
    * @param jsonData
    *            json数据
    * @param clazz
    *            对象中的object类型
    * @return
    */
   public static <T> T jsonToObject(String jsonData, Class<T> beanType) {
      return baseGson.fromJson(jsonData, beanType);
   }
   /**
    * 将json数据转换成pojo对象list
    * <p>
    * Title: jsonToList
    * </p>
    * <p>
    * Description:
    * </p>
    *
    * @param jsonData
    * @param beanType
    * @return
    */
   public static <T> List<T> jsonToList(String jsonData, Class<T> beanType) {
      if (StringUtil.isNullOrEmpty(jsonData))
         return null;
      List<T> list = new ArrayList<>();
      JSONArray array = JSONArray.fromObject(jsonData);
      for (int i = 0; i < array.size(); i++) {
         try {
            list.add(baseGson.fromJson(array.optJSONObject(i).toString(), beanType));
         } catch (Exception e) {
            list.add(baseGson.fromJson(array.optString(i), beanType));
         }
      }
      return list;
   }
}