日期格式 [ 2020, 9, 15 ]:这是什么类型的格式?

Date Format [ 2020, 9, 15 ]: What type of format is this?

我正在尝试使用有几个日期的外部 json。日期格式为:[ 2020, 9, 15 ] 我试过将它用作字符串,但没有成功。

你能告诉我这是什么格式吗

java.time

将 JSON 数字数组读入 Java int[]int 数组)并从中构造一个 LocalDate

    int[] arrayFromJson = { 2020, 9, 15 };
    System.out.println("Array from JSON: " + Arrays.toString(arrayFromJson));
    
    LocalDate date = LocalDate.of(arrayFromJson[0], arrayFromJson[1], arrayFromJson[2]);
    System.out.println("Date as LocalDate: " + date);

输出为:

Array from JSON: [2020, 9, 15]
Date as LocalDate: 2020-09-15

LocalDate 是 java.time 的 class,现代 Java 日期和时间 API,用于表示没有时间的日期,所以正确的 class 在这里使用。

读取和解析 JSON

如何把JSON读成Java?这取决于您使用哪个库来执行此操作。这是一个使用 Jackson 的例子:

    ObjectMapper mapper = new ObjectMapper();
    String json = "[ 2020, 9, 15]";

    int[] arrayFromJson = mapper.readValue(json, int[].class);
    System.out.println(Arrays.toString(arrayFromJson));
[2020, 9, 15]