标签:实体类 String public jsonPrimitive new ZonedDateTime final
今天在进行进行数据转换的时候遇到一个异常,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的问题。
标签:实体类,String,public,jsonPrimitive,new,ZonedDateTime,final 来源: https://www.cnblogs.com/daishoucheng/p/12530768.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。