zoukankan      html  css  js  c++  java
  • 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的问题。
  • 相关阅读:
    【HDOJ】4347 The Closest M Points
    【HDOJ】4341 Gold miner
    【HDOJ】4333 Revolving Digits
    【HDOJ】4336 Card Collector
    【HDOJ】4328 Cut the cake
    【HDOJ】4322 Candy
    【HDOJ】4317 Unfair Nim
    串口接收线程退出与优先级问题
    EVC编程与调试过程出现的问题
    Windows CE创建桌面快捷方式
  • 原文地址:https://www.cnblogs.com/daishoucheng/p/12530768.html
Copyright © 2011-2022 走看看