java.text.ParseException: Failed to parse date ["未知']

先把"未知"替换为""

直接new 出来的Gson 对象是无法解析为""的Date属性的,需要通过GsonBuilder来进行创建

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

}

可能还会出现报错:Invalid time zone indicator

两种结合:

Gson gson = new GsonBuilder().registerTypeAdapterFactory(new DateNullAdapterFactory<>()).setDateFormat("yyyy-MM-dd HH:mm:ss").create();

java.text.ParseException: Failed to parse date ["未知']

原文地址:https://www.cnblogs.com/fswhq/p/ParseException.html

时间: 2024-08-27 13:08:36

java.text.ParseException: Failed to parse date ["未知']的相关文章

java.text.ParseException: Unparseable date: &quot;2015-06-09 hh:56:19&quot;

1.错误描述 [DEBUG:]2015-06-09 16:56:19,520 [-------------------transcation start!--------------] java.text.ParseException: Unparseable date: "2015-06-09 hh:56:19" at java.text.DateFormat.parse(DateFormat.java:357) at sun.reflect.NativeMethodAccessor

java.text.ParseException: Unparseable date: &quot;Mon Mar 30 00:00:00 CST 2015&quot;

解决方案: package config; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Test { public static void main(String[] args) { String s="Mon Mar 30 00:00:00 CST 2015"; D

【java】Date与String之间的转换:java.text.SimpleDateFormat、public Date parse(String source) throws ParseException和public final String format(Date date)

1 package 日期日历类; 2 3 import java.text.ParseException; 4 import java.text.SimpleDateFormat; 5 import java.util.Date; 6 7 public class TestDate { 8 public static void main(String[] args) { 9 Date date=new java.util.Date(); 10 System.out.println(date);/

Java日期与时间的处理/Date,String,Calendar转换

public class Demo01 { //Java中Date类和Calendar简介 public static void main(String[] args) { long now=System.currentTimeMillis(); System.out.println("now= "+now); Date d1=new Date(now); System.out.println("d1= "+d1); Calendar c1=Calendar.get

Java之3.Math类、Date、SimpleDateFormat

/*Date date = new Date(); // 获取当前的系统时间 System.out.println("年份:"+ date.getYear());*/ /* Calendar calendar = Calendar.getInstance(); //获取当前的系统时间. System.out.println("年:"+ calendar.get(Calendar.YEAR)); System.out.println("月:"+ (

ssh整合context:component-scan包名写了*号:Failed to parse configuration class [org.springframework.cache.aspectj.AspectJJCacheConfiguration]

1 2 3 4 03-Apr-2016 00:27:57.154 WARNING [RMI TCP Connection(3)-127.0.0.1] org.springframework.web.context.support.XmlWebApplicationContext.refresh Exception encountered during context initialization - cancelling refresh attempt: org.springframework.

ASM ClassReader failed to parse class file - probably due to a new Java class file version that isn

错误产生的信息如下: Caused by: org.springframework.core.NestedIOException: ASM ClassReader failed to parse class file - probably due to a new Java class file version that isn't supported yet: file [E:\develop_tools\apache-tomcat-8.0.18\webapps\SpringMVCUpload

ASM ClassReader failed to parse class file - probably due to a new Java class file version that isn&#39;t supported yet

1. 问题描述 tomcat启动项目 报错如上,ide是eclipse,jdk安装的是jdk8. 2. 解决方案 可能原项目是用jdk7或其他版本开发的,错误提示也很清晰,更换jdk编译一下 项目右键-->build path-->Configure build path-->Project facets 再重新发布 启动好了 ASM ClassReader failed to parse class file - probably due to a new Java class fil

ASM ClassReader failed to parse class file- probably due to a new Java class file version that isn&#39;t supported yet问题

出错情况:由于接口的更改,在工程中更新了一个外部依赖的jar包,在编译启动后遇到了下述问题: Caused by: org.springframework.core.NestedIOException: ASM ClassReader failed to parse class file - probably due to a newJava class file version that isn't supported yet: URL [jar:file:/D:/project/extra-