java localdatetime解析_Java解析JSON,LocalDateTime 0000-00-00:00:00

我有个问题。我正在调用我的web服务器,它返回一个JSON字符串。在这个JSON字符串中,有几个对象如下:

public class Transaction {

private int id;

private LocalDateTime datetime;

private double quantity;

private double avgPrice;

public ArrayList parseJsonToList(String StrJSON) {

Gson gson = new GsonBuilder().registerTypeAdapter(LocalDateTime.class, (JsonDeserializer) (json, type, jsonDeserializationContext) -> {

try{

return LocalDateTime.parse(json.getAsJsonPrimitive().getAsString(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

} catch (DateTimeParseException e){

return LocalDateTime.parse(json.getAsJsonPrimitive().getAsString(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS"));

}

}).create();

Type listType = new TypeToken>() {}.getType();

return gson.fromJson(StrJSON, listType);

}

}

parseJsonToList()

方法,我创建了一个GsonBuilder,它应该将datetime从JSON转换为LocalDateTime属性(有或没有micro-time)。我现在的问题是,有些datetime值

0000-00-00 00:00:00

. 这会导致以下错误:

Exception in thread "main" java.time.format.DateTimeParseException: Text '0000-00-00 00:00:00' could not be parsed at index 19

at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2051)

at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1953)

at java.base/java.time.LocalDateTime.parse(LocalDateTime.java:493)

at com.company.Transaction.lambda$parseJsonToList$1(Transaction.java:109)

at com.google.gson.TreeTypeAdapter.read(TreeTypeAdapter.java:58)

at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:103)

at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:196)

at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:40)

at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:81)

at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:60)

at com.google.gson.Gson.fromJson(Gson.java:810)

at com.google.gson.Gson.fromJson(Gson.java:775)

at com.google.gson.Gson.fromJson(Gson.java:724)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值