【问题标题】:Define date format for @RequestBody entity without @JsonFormat为不带 @JsonFormat 的 @RequestBody 实体定义日期格式
【发布时间】:2018-02-01 09:42:46
【问题描述】:

例如我有以下课程

public class Profile {

    @JsonFormat(pattern = "dd-MM-yyyy")
    private LocalDate dateOfBirth;
    //seter, getter
}

在控制器中我使用这个类作为@ResponseBody 参数

@RestController
@RequestMapping("/profiles")
public class ProfileController {

    @RequestMapping(method = RequestMethod.POST)
    public ResponseEntity<?> createProfile(@RequestBody Profile newProfile) {
        //...
    }

}

如果我使用以下 JSON 向 /profile 发送 POST 请求,它可以正常工作

{
    "dateOfBirth": "21-01-1985"
}

如何在不使用@JsonFormat 或任何其他注释注释Profile#dateOfBirth 类的情况下实现此行为?我想将此实体用于不同的日期格式,因此我需要在 Profile 类之外定义日期格式。

【问题讨论】:

  • 您能否将 Profile 类中的所有属性设为字符串,然后转换为您计划使用该字段的特定日期格式。

标签: spring-mvc spring-boot spring-restcontroller spring-rest


【解决方案1】:

使用 Jackson 自定义反序列化。 有几种处理方法。这个博客似乎有一个很好的答案。 https://www.sghill.net/how-do-i-write-a-jackson-json-serializer-deserializer.html

【讨论】:

  • 我需要用 @JsonDeserialize@JsonSerialize 注释 Profile 类。但我不希望 Profile 类依赖于任何东西。我需要为Profile#dateOfBirth动态定义日期格式。
  • 另一种方法是拥有另一个依赖于 Jackson 的类,然后将无依赖类转换为依赖于 Jackson 的类
【解决方案2】:

您可以使用 @JsonProperty("obj-name") 。例如

public class Profile {    
    @JsonProperty("dateOfBirth")
    private LocalDate dateOfBirth;
    //seter, getter
}

Json 请求将是

{
"dateOfBirth": "21-01-1985"
}

@JsonProperty() 将直接映射特定的 json 对象字段。所以现在您可以请求任何日期格式。如果你想验证一些日期格式最好和建议的方法是Custom Annotation

希望对您有帮助...

干杯...

【讨论】:

    猜你喜欢
    • 2014-07-31
    • 1970-01-01
    • 2022-12-19
    • 2021-05-14
    • 1970-01-01
    • 2021-10-22
    • 2021-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多