Я новичок в использовании Jackson, и я пытаюсь следовать шаблонам моей команды для десериализации нашего JSON. Прямо сейчас я сталкиваюсь с проблемой, когда имя поля не соответствует свойству JSON.
Рабочий пример:
@JsonDeserialize(builder = ProfilePrimaryData.Builder.class)
@Value
@ParametersAreNonnullByDefault
@Builder(builderClassName = "Builder")
private static class ProfilePrimaryData {
private final Boolean hasProfile;
@JsonPOJOBuilder(withPrefix = "")
public static class Builder {
}
}
Если свойство JSON имеет значение hasProfile, оно работает нормально, но если оно имеет значение has_profile (это то, что пишет наш клиент), оно не работает, и я получаю сообщение об ошибке: Unrecognized field "has_profile" (class com.mypackagehere.something.$ProfilePrimaryData$Builder), not marked as ignorable (one known property: "hasProfile"]). Я пробовал добавить аннотацию JsonProperty в hasProfile, как это, но она все еще не работает:
@JsonDeserialize(builder = ProfilePrimaryData.Builder.class)
@Value
@ParametersAreNonnullByDefault
@Builder(builderClassName = "Builder")
private static class ProfilePrimaryData {
@JsonProperty("has_profile")
private final Boolean hasProfile;
@JsonPOJOBuilder(withPrefix = "")
public static class Builder {
}
}
Я неправильно понимаю, как это должно работать?
@SASIKUMARS - Я не думаю, что мы на одной странице - я хочу, чтобы поле has_profile было прочитано и помещено в поле hasProfile в POJO. Разве JsonIgnoreProperties не просто выбросит значение?
вы можете опубликовать образец JSON?





Ошибка четко говорит, что Unrecognized field "has_profile" (class com.mypackagehere.something.$ProfilePrimaryData$Builder)
т.е. has_profile отсутствует в классе Builder, а не в классе ProfilePrimaryData, поэтому вам нужно аннотировать свойства класса Builder.
@JsonDeserialize(builder = ProfilePrimaryData.Builder.class)
public class ProfilePrimaryData {
/*
* This annotation only needed, if you want to
* serialize this field as has_profile,
*
* <pre>
* with annotation
* {"has_profile":true}
*
* without annotation
* {"hasProfile":true}
* <pre>
*
*/
//@JsonProperty("has_profile")
private final Boolean hasProfile;
private ProfilePrimaryData(Boolean hasProfile) {
this.hasProfile = hasProfile;
}
public Boolean getHasProfile() {
return hasProfile;
}
@JsonPOJOBuilder(withPrefix = "")
public static class Builder {
// this annotation is required
@JsonProperty("has_profile")
private Boolean hasProfile;
public Builder hasProfile(Boolean hasProfile) {
this.hasProfile = hasProfile;
return this;
}
public ProfilePrimaryData build() {
return new ProfilePrimaryData(hasProfile);
}
}
}
Это может вам помочь - аннотация уровня класса stackoverflow.com/questions/16019834/… или
@JsonIgnoreProperties(value = { "has_profile" })или, если быть более универсальным,@JsonIgnoreProperties(ignoreUnknown = true)