LinkedHashMap转成实体类时遇到String转ZonedDateTime异常

  今天在进行进行数据转换的时候遇到一个异常,java.util.LinkedHashMap cannot be cast to xxx,其中最关键的就是Expected BEGIN_OBJECT but was STRING at line 1 column 644 path $[0].validEndDateTime。异常原因已经很详细了,就是在转换的时候String类型的数据转换成ZonedDateTime出现的问题。经过google之后,我使用如下的办法解决Bug。

  引用jar包:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
</dependency>

 

  工具类

public class GsonUtil {
    public static final JsonDeserializer<ZonedDateTime> ZDT_DESERIALIZER = new JsonDeserializer<ZonedDateTime>() {
        @Override
        public ZonedDateTime deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException {
            JsonPrimitive jsonPrimitive = json.getAsJsonPrimitive();
            try {
                // if provided as String - '2011-12-03T10:15:30+01:00[Europe/Paris]'
                if(jsonPrimitive.isString()){
                    return ZonedDateTime.parse(jsonPrimitive.getAsString(), DateTimeFormatter.ISO_ZONED_DATE_TIME);
                }
                // if provided as Long
                if(jsonPrimitive.isNumber()){
                    return ZonedDateTime.ofInstant(Instant.ofEpochMilli(jsonPrimitive.getAsLong()), ZoneId.systemDefault());
                }
            } catch(RuntimeException e){
                throw new JsonParseException("Unable to parse ZonedDateTime", e);
            }
            throw new JsonParseException("Unable to parse ZonedDateTime");
        }
    };
}

 

运行code

List<TicketAndPassEntitlement> ticketList = new GsonBuilder()
        .registerTypeAdapter(ZonedDateTime.class, GsonUtil.ZDT_DESERIALIZER)
        .create()
        .fromJson(new Gson().toJson(resourceList), new TypeToken<List<TicketAndPassEntitlement222>>(){}.getType());

 

解释: 

new Gson().toJson(resourceList)的目的是将List<LinkedHashMap>转换成Gson格式的数据。
GsonUtil工具类是为了解决String转成ZonedDateTime的问题。

 

posted @ 2020-03-20 11:56  技术博客这里开始  Views(699)  Comments(0Edit  收藏  举报