http://hi.baidu.com/yuji0228/blog/item/394f86395fc0113eb9998f30.html
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"));
}