简体   繁体   English

用杰克逊解析嵌套对象

[英]Parsing nested objects with Jackson

I am using Robospice + Retrofit + Jackson. 我正在使用Robospice + Retrofit + Jackson。 I have not plain class which has another class object as a field. 我没有普通的类,它有另一个类对象作为字段。 I need to parse json and create class with field. 我需要解析json并使用field创建类。
Here is my class 这是我的课

@JsonIgnoreProperties(ignoreUnknown=true)
public class User implements UserInformationProvider {
    @JsonProperty("customer_id")
    public int id;
    @JsonProperty("firstname")
    public String firstName;
    @JsonProperty("lastname")
    public String lastName;
    @JsonProperty("email")
    public String email;
    @JsonProperty("telephone")
    public String phone;
    @JsonProperty("token_api")
    public String token;
    @JsonProperty("token_expire")
    public int tokenExpireTime;
    public UserPreferences userPreferences;
    @Override
    public String getUserFirstName() {
        return firstName;
    }

    @Override
    public String getUserLastName() {
        return lastName;
    }

    @Override
    public String getUserEmail() {
        return email;
    }

    @Override
    public String getUserIconUrl() {
        return null;
    }
}

And preferences class 和偏好类

public class UserPreferences {
    public boolean offersNotifications;
    public boolean statusChangedNotifications;
    public boolean subscriptionNotifications;
    @JsonProperty("new_offers")
    public boolean newOffersNotify;
    @JsonProperty("order_status_changed")
    public boolean orderStatusChangedNotify;
    @JsonProperty("hot_offers")
    public boolean hotOffersNotify;
}

Request that I need to parse into POJO. 请求我需要解析到POJO。

{
    "customer_id": 84,
    "token_api": "ef5d7d2cd5dfa27a",
    "token_expire_unix": "1435113663",
    "preferences": {
        "new_offers": "1",
        "order_status_changed": "1",
        "hot_offers": "1"
    }
}

Please help, how can I do this using Jackson. 请帮忙,我怎么能用杰克逊做到这一点。 I would be very grateful for any help. 我会非常感谢任何帮助。 Thanks in advance. 提前致谢。

The main problem lies inside of UserPreferences . 主要问题在于UserPreferences Right now your code is attempting to deserialize "1" as a boolean . 现在你的代码试图将"1"反序列化为boolean Java will not do this translation for you, so you will need to create a custom deserializer and apply it to the fields with numeric booleans. Java不会为您执行此转换,因此您需要创建自定义反序列化器并将其应用于具有数字布尔值的字段。

Create a Custom Deserializer 创建自定义反序列化器

A deserializer allows you to specify a class and apply custom operations to how it is created from JSON: 反序列化器允许您指定一个类并将自定义操作应用于如何从JSON创建它:

public class NumericBooleanDeserializer extends JsonDeserializer<Boolean> {
    @Override
    public Boolean deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        int intValue = p.getValueAsInt();
        switch (intValue) {
            case 0:
                return Boolean.TRUE;
            case 1:
                return Boolean.FALSE;
            default:
                // throw exception or fail silently
        }
        return null; // can throw an exception if failure is desired
    }
}

Apply Custom Deserialization to Fields 将自定义反序列化应用于字段

Since you probably don't want to register this on your ObjectMapper and apply it to all deserialization, you can use the @JsonDeserialize annotation. 由于您可能不希望在ObjectMapper上注册它并将其应用于所有反序列化,因此可以使用@JsonDeserialize注释。 Your UserPreferences class will end up looking something like this: 您的UserPreferences类最终会看起来像这样:

public class UserPreferences {
    public boolean offersNotifications;
    public boolean statusChangedNotifications;
    public boolean subscriptionNotifications;

    @JsonProperty("new_offers")
    @JsonDeserialize(using = NumericBooleanDeserializer.class)
    public boolean newOffersNotify;

    @JsonProperty("order_status_changed")
    @JsonDeserialize(using = NumericBooleanDeserializer.class)
    public boolean orderStatusChangedNotify;

    @JsonProperty("hot_offers")
    @JsonDeserialize(using = NumericBooleanDeserializer.class)
    public boolean hotOffersNotify;
}

Make Sure @JsonProperty Matches JSON Keys 确保@JsonProperty匹配JSON密钥

Since your JSON has "preferences" and the name of your Java property is userPreferences you will need to slap a @JsonProperty("preferences") on the property inside of User 由于您的JSON具有"preferences"并且您的Java属性的名称是userPreferences您需要在User内部的属性上打一个@JsonProperty("preferences")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM