Gson将字符串转换为Date类型

自定义DateAdapter

public class DateAdapter implements JsonDeserializer<Date> {
	private final DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
	public Date deserialize(JsonElement arg0, Type arg1,
			JsonDeserializationContext arg2) throws JsonParseException {
		try {
			return df.parse(arg0.getAsString());
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}
}

  然后在代码中创建转换器即可:

Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new DateAdapter()).create();

posted @ 2014-12-08 13:49  小房  阅读(2511)  评论(0编辑  收藏  举报