解决:Gson无法解析Date传值为""的问题(Failed to parse date ["']: (java.lang.NumberFormatException))

直接new 出来的Gson 对象是无法解析为""的Date属性的.

需要通过GsonBuilder来进行创建.

static Gson ignoreDateGson=new GsonBuilder().registerTypeAdapterFactory(new DateNullAdapterFactory<>()).create();

这个registerTypeAdapterFactory()方法就是添加自己的适配器,来对某些特定的类型进行处理.

new 出来的这个DateNullAdapterFactory.class 需要自己写.

import java.util.Date;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;

public class DateNullAdapterFactory<T> implements TypeAdapterFactory {
	
    @SuppressWarnings("unchecked")
    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
        Class<T> rawType = (Class<T>) type.getRawType();
        if (rawType != Date.class) {
            return null;
        }
        return (TypeAdapter<T>) new DateNullAdapter();
    }
}

这个是为了指定什么类型的属性需要进行处理.真正处理的Date 的操作是在DateNullAdapter 里面.

以下是这个类的代码.

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.util.Date;
import java.util.Locale;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.internal.bind.DateTypeAdapter;
import com.google.gson.internal.bind.util.ISO8601Utils;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import com.zxtc.common.utils.StringUtils;

public class DateNullAdapter extends TypeAdapter<Date>{
	
	  public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() {
		    @SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal
		    @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
		      return typeToken.getRawType() == Date.class ? (TypeAdapter<T>) new DateTypeAdapter() : null;
		    }
		  };

		  private final DateFormat enUsFormat
		      = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.US);
		  private final DateFormat localFormat
		      = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT);

		  @Override public Date read(JsonReader in) throws IOException {
			  
		    if (in.peek() == JsonToken.NULL) {
		      in.nextNull();
		      return null;
		    }
		    String jsonStr = in.nextString();
		    if(StringUtils.isBlank(jsonStr)) {
		    	return null;
		    }else {
		    	return deserializeToDate(jsonStr);
		    }
		  }

		  private synchronized Date deserializeToDate(String json) {
		    try {
		      return localFormat.parse(json);
		    } catch (ParseException ignored) {
		    }
		    try {
		      return enUsFormat.parse(json);
		    } catch (ParseException ignored) {
		    }
		    try {
		    	return ISO8601Utils.parse(json, new ParsePosition(0));
		    } catch (ParseException e) {
		      throw new JsonSyntaxException(json, e);
		    }
		  }

		  @Override public synchronized void write(JsonWriter out, Date value) throws IOException {
		    if (value == null) {
		      out.nullValue();
		      return;
		    }
		    String dateFormatAsString = enUsFormat.format(value);
		    out.value(dateFormatAsString);
		  }
		  
		  
}

接下来就可以进行反序列化了.

做一个例子:

import java.util.Date;

public class User {
	
	private String name;
	private Date birth;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Date getBirth() {
		return birth;
	}
	public void setBirth(Date birth) {
		this.birth = birth;
	}
}

对两种gson创建方式进行对比.

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class Test {
	public static void main(String[] args) {
		Gson ignoreDateGson=new GsonBuilder().registerTypeAdapterFactory(new DateNullAdapterFactory<>()).create();
		Gson gson =new GsonBuilder().create();
		String  str = "{\"name\":\"张三\",\"birth\":\"\"}";
		User t1 = ignoreDateGson.fromJson(str, User.class);
//		User t2 = gson.fromJson(str, User.class);
		System.out.println(t1.getBirth());
		
	}
}

上边的方法输出为null,

下边的方法直接报错.



  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值