java - 如何使用Gson序列化LocalDate?

标签 java json spring serialization gson

我有以下POJO:

public class Round {

    private ObjectId _id;

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
    @JsonDeserialize(using = LocalDateDeserializer.class)
    @JsonSerialize(using = LocalDateSerializer.class)
    @Getter
    @Setter
    @Accessors(fluent = true)
    @JsonProperty("date")
    private LocalDate date;

    // rest of fields

}

将 POJO 转换为 JSON 的序列化方法:

public static String toJson(Object object){
    return new Gson().toJson(object);
}

但是,当我调用 toJson 方法时,如下所示:

     Round round = new Round()
            .userId("user3")
            .course("course 1")
            .date(LocalDate.now())
            .notes("none");
    }

     return MockMvcRequestBuilders
                .post("/rounds")
                .accept(MediaType.APPLICATION_JSON)
                .content(TestHelper.toJson(round))
                .contentType(MediaType.APPLICATION_JSON);

我收到错误:com.fasterxml.jackson.databind.exc.MismatchedInputException,它引用了 POJO 的日期字段:

2020-04-25 21:19:22.269  WARN 6360 --- [           main] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Expected array or string.; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Expected array or string.
     at [Source: (PushbackInputStream); line: 1, column: 47] (through reference chain: com.ryd.golfstats.golfstats.model.Round["date"])]

如何使用 Gson 正确序列化 LocalDate 字段?

最佳答案

您的 POJO 使用 Jackson JSON 库中的注释,因此您应该使用其设施来序列化 LocalDate,然后一切都会正常工作:

Round r = new Round();
r.set_id(1);
r.setDate(LocalDate.now());
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
String rjson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(r);
System.out.println(rjson);

产生:

{
  "_id" : 1,
  "date" : "26-04-2020"
}

如果您因为某些原因需要使用Gson,可以查看this answer ,为LocalDate提供适配器并注册到Gson:

class LocalDateAdapter implements JsonSerializer<LocalDate> {

    public JsonElement serialize(LocalDate date, Type typeOfSrc, JsonSerializationContext context) {
        return new JsonPrimitive(date.format(DateTimeFormatter.ISO_LOCAL_DATE)); // "yyyy-mm-dd"
    }
}
// -------
Gson gson = new GsonBuilder()
        .setPrettyPrinting()
        .registerTypeAdapter(LocalDate.class, new LocalDateAdapter())
        .create();

关于java - 如何使用Gson序列化LocalDate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61432170/

相关文章:

java - Selenium webdriver 通过匹配来自其他列的文本来获取同一行中相邻列的文本

java - 无法写入内容: failed to lazily initialize a collection of role using OpenEntityManagerInViewFilter

javascript - 在 Javascript 中制作图表 - 问题

javascript - Google Chrome 扩展程序 - 未找到指定的 native 消息传递主机

java - 带有 Jetty 的 Spring MVC - app-servlet.xml 文件中应该包含什么?

java - 如何从 XFire AbstractHandler 的 invoke() 方法中获取 ServletRequest 对象?

java - 使用 JPA 2.0 以编程方式加载实体类?

java - 这个简单查询中正确的 where 条件..我缺少什么?

javascript - JSON 中对象文字的另一种形式?

java - 登录 Spring 初始化