首页 > 解决方案 > JSON 属性未从 Spring Boot 中的不同名称反序列化

问题描述

这是我的 POJO:

import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.cloud.Timestamp;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class Course {

    private String code;

    private int credits;

    private int id;

    @JsonProperty("last_updated")
    private Timestamp lastUpdated;

    private String name;

    private String prerequisites;

    private String restrictions;

    private Seats seats;

    private Seats waitlist;
}

我正在从 Firestore 读取数据,这些数据被隐式映射到此类。

显着的区别是last_updated在 Firestore 中有一个下划线:

在此处输入图像描述

但我希望 JSON 反序列化为lastUpdated没有下划线。我认为这就是重点,@JsonProperty但这里发生的只是我得到了一个空值:

在此处输入图像描述

以及 Spring Boot 中的以下日志记录:

2020-06-18 03:44:36.852  WARN 5200 --- [nio-8080-exec-1] c.g.cloud.firestore.CustomClassMapper    : No setter/field for last_updated found on class ....dto.Course
2020-06-18 03:44:36.852  WARN 5200 --- [nio-8080-exec-1] c.g.cloud.firestore.CustomClassMapper    : No setter/field for last_updated found on class ....dto.Course
2020-06-18 03:44:36.853  WARN 5200 --- [nio-8080-exec-1] c.g.cloud.firestore.CustomClassMapper    : No setter/field for last_updated found on class ....dto.Course

我已经对其进行了调试,并确认在 Java 世界中,lastUpdated它始终为空。

如何让我的 POJO 反序列last_updated化到lastUpdatedPOJO 字段中,而不必将 POJO 属性重命名为last_updated(这有效,但违反了很多 linting 原则)?

标签: jsonspringspring-bootgoogle-cloud-firestorejackson

解决方案


你可以这样写你的财产

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ")
private Date createdDate;

Date是一个很好的字段类型。您可以使用以下方法非常轻松地使 JSON 可解析ObjectMapper.setDateFormat

DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm a z");
myObjectMapper.setDateFormat(df);

推荐阅读