gson日期转换和解析数组

http://hi.baidu.com/sword0228/item/bd33e5997f2a9bdd7b7f0196

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();
 
 public static String bean2json(Object bean) {
  return gson.toJson(bean);
 }

 public static <T> T json2bean(String json, Type type) {
  return gson.fromJson(json, type);
 }
 
 private static class UtilDateSerializer 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());
  }

 }
 
 private static class UtilCalendarSerializer 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;
  }
  
 }

 

 

 

 

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

posted @ 2012-08-20 14:36  balaamwe  阅读(2047)  评论(0编辑  收藏  举报