我正在使用Robospice Retrofit Jackson.我沒有普通的類,它有另一個類對象作為字段.我需要解析json并使用field建立類.
這是我的課
@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"
}
}
請幫忙,我怎麼能用傑克遜做到這一點.我會非常感謝任何幫助.提前緻謝.
最佳答案 主要問題在于UserPreferences.現在你的代碼試圖将“1”反序列化為布爾值. Java不會為您執行此轉換,是以您需要建立自定義反序列化器并将其應用于具有數字布爾值的字段.
建立自定義反序列化器
反序列化器允許您指定一個類并将自定義操作應用于如何從JSON建立它:
public class NumericBooleanDeserializer extends JsonDeserializer {
@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
}
}
将自定義反序列化應用于字段
由于您可能不希望在ObjectMapper上注冊它并将其應用于所有反序列化,是以可以使用@JsonDeserialize注釋.您的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;
}
確定@JsonProperty比對JSON密鑰
由于您的JSON具有“首選項”并且您的Java屬性的名稱是userPreferences,是以您需要在User内部的屬性上打一個@JsonProperty(“preferences”)