首页 > 解决方案 > Java 使用 LocalDateTime 0000-00-00 00:00:00 解析 JSON

问题描述

我有个问题。我正在调用我的网络服务器,它返回一个 JSON 字符串。在这个 JSON 字符串中,我有一些像这样的对象:

public class Transaction {

    private int id;
    private LocalDateTime datetime;
    private double quantity;
    private double avgPrice;

    public ArrayList<Transaction> parseJsonToList(String StrJSON) {
    
        Gson gson = new GsonBuilder().registerTypeAdapter(LocalDateTime.class, (JsonDeserializer<LocalDateTime>) (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<ArrayList<Transaction>>() {}.getType();
    
        return gson.fromJson(StrJSON, listType);
    
    }
    
}

现在,当我调用该parseJsonToList()方法时,我创建了一个 GsonBuilder,它应该将日期时间从我的 JSON 转换为 LocalDateTime 属性(有或没有微时间)。我现在遇到的问题是一些日期时间值是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)

现在我无法更改 JSON,那么有没有办法我仍然可以存储它或使用空值?

标签: javajsongsonjava-timedatetimeformatter

解决方案


您可以使用DateTimeFormatter#withResolverStyle(ResolverStyle.LENIENT)

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.ResolverStyle;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss", Locale.ENGLISH)
                .withResolverStyle(ResolverStyle.LENIENT);
        String str = "0000-00-00 00:00:00";

        LocalDateTime ldt = LocalDateTime.parse(str, dtf);
        System.out.println(ldt);
    }
}

输出:

-0001-11-30T00:00

推荐阅读