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();

时间: 2024-08-26 15:34:56

Gson将字符串转换为Date类型的相关文章

把字符串转换为Double 类型

//把字符串转换为Double 类型    public Double convertStringToDouble(String value){                      Double doubleValue = new Double("0.00");           if(value != null && !"".equals(value))              doubleValue = new Double(value

Java:String转换为date类型

public static Date stringToDate(String str) { DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Date date = null; try { // Fri Feb 24 00:00:00 CST 2012 date = format.parse(str); } catch (ParseException e) { e.printStackTrace(); } // 2012-0

Oracle 日期型 将timestamp类型转换为date类型

Oracle将timestamp类型转换为date类型有三种方法 1.使用to_char先转为字符型,在使用to_date再转为日期型 select to_date(to_char(systimestamp,'yyyy/mm/dd hh24:mi:ss'),'yyyy/mm/dd hh24:mi:ss') from dual; 2.使用SYSTIMESTAMP+0隐式转换 select systimestamp+0 from dual;                    --oracle会自

字符串转换为数字类型

// @param s为字符串,n为数字function fn(obj){    //转换为String类型    var s = obj +"";    //转换为number类型    var n = +obj;}

不使用java内置函数,将String字符串转换为int类型

package com.test; public class AtoiTest { public static void main(String[] args) throws Exception { String s = "-011134"; System.out.println("转换前的字符串:" + s); System.out.println("atoi1转换后的字符串:" + atoi1(s)); System.out.println(

如何实现@ResponseBody,把Json字符串转换为指定类型

1.问题 spring 是如何把 http中的body,转换为指定类的,里面的难点其实在于泛型的处理. 2.Spring的处理 2.1 HandlerMethod 这个类Spring对Method的封装,例如使用@RequestMapping注解方法,会使用HandlerMethod封装(其实是其子类InvocableHandlerMethod).然后由InvocableHandlerMethod对其进行调用 HandlerMethod的属性如下 private final Object bea

java中字符串转换Date类型

1 public static Date date(String date_str) { 2 try { 3 Calendar zcal = Calendar.getInstance();//日期类 4 Timestamp timestampnow = new Timestamp(zcal.getTimeInMillis());//转换成正常的日期格式 5 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");/

将yyyyMMdd,dd/MM/yyyy 类型字符串转换为datetime 类型 yyyy-MM-dd C#

DateTime ConvertDate = DateTime.ParseExact("20140504", "yyyyMMdd", null, System.Globalization.DateTimeStyles.AllowWhiteSpaces).ToString("yyyy-MM-dd"); DateTime.ParseExact("18/05/2014", "dd/MM/yyyy", System

金蝶KIS新建账套时 从字符串向DateTime转换时失败 从字符串转换为Datetime类型时发生语法错误

需要修改以下几点 控制面板---区域和语言选项---区域选项---自定义,修改为如下格式