用Jackson解析嵌套对象
我正在使用Robospice+改装+Jackson。我没有一个普通类,它有另一个类对象作为字段。我需要解析json并创建带有字段的类
这是我的班级
@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;
}
}
和偏好类
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;
}
我需要解析为POJO的请求
{
"customer_id": 84,
"token_api": "ef5d7d2cd5dfa27a",
"token_expire_unix": "1435113663",
"preferences": {
"new_offers": "1",
"order_status_changed": "1",
"hot_offers": "1"
}
}
请帮帮我,我怎样才能用Jackson做到这一点。我将非常感谢任何帮助。提前谢谢
# 1 楼答案
主要问题在于
UserPreferences
的内部。现在,您的代码正试图将"1"
反序列化为boolean
。Java不会为您执行此转换,因此您需要创建一个自定义反序列化程序,并将其应用于带有数字布尔值的字段创建自定义反序列化程序
反序列化程序允许您指定一个类,并将自定义操作应用于如何从JSON创建该类:
将自定义反序列化应用于字段
由于您可能不想在
ObjectMapper
上注册它并将其应用于all反序列化,因此可以使用@JsonDeserialize
注释。您的UserPreferences
类将以如下方式结束:确保
@JsonProperty
匹配JSON键由于JSON具有
"preferences"
,并且Java属性的名称为userPreferences
,因此需要在User
内的属性上加上@JsonProperty("preferences")