其余API调用使用LocalDate返回错误

时间:2019-06-06 11:51:05

标签: java json rest spring-boot jackson-databind

我正在尝试进行一次REST API调用,但一直得到App/Http/Controllers/phpseclib/Crypt/RSA.php。从日志来看,我的POJO的400 Bad Request字段之一似乎有问题。

我的POJO:

LocalDate

在我的public class MyObj implements Serializable { private Long id; private String remark; private LocalDate someDate; ...other fields, getter and setter

main()

运行上面的代码,我得到以下错误: MyObj myObj = new MyObj(); myObj .setRemark("My test case"); myObj .setSomeDate( LocalDate.now()); ... WebResource webResource = client .resource("my_url"); webResource .header("apikey", "mykey") .accept("application/json") .type("application/json") .post(MyObj.class, myObj );

您知道为什么发生上述情况吗?

2 个答案:

答案 0 :(得分:1)

LocalDate应该在序列化时转换为字符串,并在反序列化时转换回LocalDate。为此,您可以在对象LocalDate属性上使用@JsonSerialize@JsonDeserialize(using = LocalDateDeserializer.class) @JsonSerialize(using = LocalDateSerializer.class) private LocalDate someDate;

JavaTimeModule()

有关更多信息,请参见以下链接: https://kodejava.org/how-to-format-localdate-object-using-jackson

另一种方法是使用ObjectMapper并注册模块ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JavaTimeModule());

void foo(String myString) {
    /*
        Here we're making myString upper case and checking if it begins w/ 0x.
        If the string starts with 0X, that'll be replaced with an empty string.
    */
    if ((myString = myString.ToUpperCase()).startsWith("0X")) {
        myString = myString.replace("0X", "");
    }

    String parsedHex = Long.toHexString(Long.parseLong(myString, 16 /* This is the radix (base) of the number. In this case we want hex (16) */));
    System.out.println(String.format("0x%s%s", parsedHex.length() % 2 == 0 ? "" : "0" /* If it's an odd number, add a leading zero. */, parsedHex));

}

使用ObjectMapper和类似问题的示例: https://groups.google.com/forum/#!topic/jackson-user/XdHvRKG1vhY

答案 1 :(得分:0)

您需要注释LocalDate,以告知应如何将其转换为String。这是ZonedDateTime的代码段,但是您要做的就是更改掩码以适合LocalDate。

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ")
public ZonedDateTime getTime() {
    return time;
}

以下是原始问题的链接:Spring Data JPA - ZonedDateTime format for json serialization