Jackson JSON使用不同的字段名称反序列化+ Builder?

时间:2018-06-11 23:04:08

标签: jackson json-deserialization

我很擅长使用杰克逊,而我正试图遵循我的团队模式来反序化我们的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 {
    }
}

我是否误解了这应该如何运作?

1 个答案:

答案 0 :(得分:1)

错误清楚地表明Unrecognized field "has_profile" (class com.mypackagehere.something.$ProfilePrimaryData$Builder
has_profile类缺少Builder,而ProfilePrimaryData类缺少@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); } } } ,因此您必须注释Builder类属性。

@Query(value ="MATCH (n:Phone {phoneId:{0}})-[f:calling*0..{1}]-(m) OPTIONAL MATCH (m)-[r]-() return m,r")  
List<QueryPOJO> graph(String name,int level);