Java将json字段解析为Period [英] Java parsing json fields into Period

查看:131
本文介绍了Java将json字段解析为Period的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的json响应如下:

If I have a json response that looks like this:

{
    year: 40,
    month: 2,
    day: 21
}

代表某人的年龄。我有一个课程来存储:

That represents someone's age. And I have a class to store that:

public class User {
    private Period age;
}

如何解析单个数字并创建期间对象?

How do I parse the individual numbers and create a Period object?

推荐答案

您应该实现客户反序列化程序。请参阅 Awita的回答

You should implement a customer deserializer. See the Awita's answer.

然而,仅供记录,有官方数据类型Jackson模块,它识别Java 8 Date& Time API数据类型。它将 Period 表示为ISO-8601格式的字符串,而不是您声明的对象。但如果您愿意更改格式,可以考虑使用该模块。

However, just for the record, there is an official datatype Jackson module which recognizes Java 8 Date & Time API data types. It represents Period as a string in the ISO-8601 format, not as object your stated. But if you are willing to change the format, you can consider using that module.

以下是一个示例:

public class JacksonPeriod {
    public static void main(String[] args) throws JsonProcessingException {
        final ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule());
        final Period period = Period.of(1, 2, 3);
        final String json = objectMapper.writeValueAsString(period);
        System.out.println(json);
    }
}

输出:

"P1Y2M3D"

这篇关于Java将json字段解析为Period的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆