Google GSON应用 - gson进行日期转换及解析数组

以下是相关伪代码

1. 构建Gson对象的时候指定相关的日期格式:

private static Gson gson = new GsonBuilder().registerTypeAdapter(Date.class,
   new UtilDateSerializer()).registerTypeAdapter(Calendar.class,
   new UtilCalendarSerializer()).registerTypeAdapter(GregorianCalendar.class,
   new UtilCalendarSerializer())
   .setDateFormat(DateFormat.LONG).setPrettyPrinting()
   .create();

 2. 将Object转换为Json String

 public static String bean2json(Object bean) {
      return gson.toJson(bean);
 }

 3. 将Json转换为Object

 public static <T> T json2bean(String json, Type type) {
      return gson.fromJson(json, type);
 }

4.1、日期处理(Date)

private static class DateSerializerUtil implements   JsonSerializer<Date>,JsonDeserializer<Date> {

  @Override
  public JsonElement serialize(Date date, Type type,
    JsonSerializationContext context) {
   return new JsonPrimitive(date.getTime());
  }
  
  @Override
  public Date deserialize(JsonElement element, Type type, JsonDeserializationContext context)
    throws JsonParseException {
   return new Date(element.getAsJsonPrimitive().getAsLong());
  }

 }
 
 

4.2、日期处理(Calendar)

private static class DateSerializerUtil2 implements JsonSerializer<Calendar>,JsonDeserializer<Calendar> {

  @Override
  public JsonElement serialize(Calendar cal, Type type,
    JsonSerializationContext context) {
   return new JsonPrimitive(Long.valueOf(cal.getTimeInMillis()));
  }

  @Override
  public Calendar deserialize(JsonElement element, Type type,
    JsonDeserializationContext context) throws JsonParseException {
   Calendar cal = Calendar.getInstance();
   cal.setTimeInMillis(element.getAsJsonPrimitive().getAsLong());
   return cal;
  }
  
 }

 5、解析Json 数组型的字符串

 
 JsonArray jsonarray = new JsonParser().parse(jsonOrXmlData).getAsJsonArray("TopAds");
   for (int i = 0; i < jsonarray.size(); i++) {
             JsonObject obj = jsonarray.get(i).getAsJsonObject();
             System.out.println(obj.get("HeadLine"));
         }

猜你喜欢

转载自josh-persistence.iteye.com/blog/1989249