【问题标题】:Jackson - How to parse this field?Jackson - 如何解析这个字段?
【发布时间】:2015-09-10 04:15:54
【问题描述】:

我有以下 JSON(来自 WebService):

{
    "result": "success",
    "users": [{
        "id": 12345,
        "login": "blabla",
        "firstName": "first name here",
        "lastName": "last name here",
        "companyName": "company here",
        "email": "email_here@test.com",
        "phone": "",
        "mobile": "123456789",
        "locations": [{
            "id": 123123,
            "latitude": 23.330196,
            "longitude": -92.026073,
            "timestamp": "2015-08-17T01:43:21+00:00"
        }],
        "status": {
            "message": "Message here",
            "timestamp": "2015-07-31T01:50:51+00:00"
        }
    }, (...)

我还有以下 bean:

@JsonTypeName("user")
public class User implements IdentityInterface
{
    private long id;

    @JsonProperty
    private String firstName;

    (...)

    //How can I anotate this field?
    private double latitude;

    //How can I anotate this field?
    private double longitude;

    (...)
}

我不能只将@JsonProperty 放在纬度/经度变量中,因为这些值在 JSON 的“位置”部分内。

如何在此处使用 Jackson 注释纬度/经度字段?

【问题讨论】:

    标签: java json parsing annotations jackson


    【解决方案1】:

    您需要像这样在您的用户类中创建一个位置列表。

    @JsonTypeName("user")
    public class User implements IdentityInterface
    {
        private long id;
    
        @JsonProperty
        private String firstName;
    
        (...)
    
        @JsonProperty
        private List<Location> locations;
    }
    public class Location{
        private Long id;
        private Double latitude;
        private Double longitude;
        private Date timestamp;
    
        // Getters and setter
       (...)
    }
    

    【讨论】:

    • 感谢您的回复。不幸的是,我不能像那样更改字段。它们已经全部映射到数据库和其他数据结构。在这一点上改变这种结构是不切实际的。我需要一种方法来注释它们并使字段保持原样。
    • 您可以创建一个映射到 json 的 bean,然后选择您需要的值并将其格式化为您想要的 db 持久性。
    • 我真的不想复制字段(无论是在同一个类上还是通过创建一个新类)才能做到这一点。必须有另一种解决方案。
    • 好的...请在得到解决方案后发表评论。我也想知道:)
    猜你喜欢
    • 2014-10-04
    • 2015-05-20
    • 2011-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-29
    • 2013-11-03
    相关资源
    最近更新 更多