gson日期转换和解析数组

阅读 38

2023-04-11




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"));
         }

精彩评论(0)

0 0 举报