【问题标题】:Retrofit interface deserialization改造接口反序列化
【发布时间】:2021-03-14 09:45:26
【问题描述】:

我有一个响应对象,它始终包含响应对象作为属性和不同类型的值,因此我在一个类中将接口作为一个字段,这样它将基于一些唯一值标识符带来正确的实现。

Could not execute the callcom.fasterxml.jackson.databind.exc.InvalidTypeIdException: Missing type id when trying to resolve subtype of [simple type, class com.opngo.nowos.nowos.api.response.DataResponse]: missing type id property 'operation' (for POJO property 'response')
 at [Source: (okhttp3.ResponseBody$BomAwareReader); line: 1, column: 180] (through reference chain: com.opngo.nowos.nowos.NowOSResponse["response"])

这是我的界面

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "operation")
@JsonSubTypes({@JsonSubTypes.Type(value = AuthResponse.class, name = "account_auth")})
public interface IResponse {
    ///
}

这是实现上述接口的响应对象之一

@RequiredArgsConstructor
public class AuthResponse implements IResponse {

    @JsonProperty
    private final String accountID;
    @JsonProperty
    private final String authToken;
    @JsonProperty
    private final String language;
}

这是具有应该带来正确响应对象的接口的主要响应

    public class NowOSResponse {

    @JsonProperty
    private final String operation;
    @JsonProperty
    private final String version;
    @JsonProperty
    private final IResponse response;
    @JsonProperty
    private final String status;

}

看起来它没有查看父项并在 AuthResponse 中搜索操作字段,该字段当然是空的,因为操作字段始终存在于父项中并且该父项具有响应 -> AuthResponse ->CreateAccResponse 等等

【问题讨论】:

    标签: java json jackson retrofit jackson-databind


    【解决方案1】:

    我想发布一个解决方案,希望对您有所帮助。

    如果您在对象中有一个始终返回不同属性的对象,您可以使用以下方法:

    1)创建一个抽象类,例如 MainResponse,该响应将包含状态和操作,因为属性是常量

    public abstract class MainResponse {
    
        @JsonProperty
        private String version;
        
        public abstract IResponse getResponse(); // so we declaring it abstract so that all the childrens have to override it in order to return specific interface realisation
    
    }
    

    现在我们必须创建一个特定的响应体,该响应体应该基于 api 调用返回。

    @Getter
    @JsonIgnoreProperties(ignoreUnknown = true)
    public class AuthResponse implements IResponse {
    
        @JsonProperty
        private String accountID;
        @JsonProperty
        private String authToken;
    
    }
    

    现在由于 json 需要响应 json 属性,我们必须创建一个额外的类来扩展抽象类,这意味着我们将拥有需要 IResponse 作为返回的 getResponse,因此我们在 AuthResponse 中实现了该接口,我们可以简单地将 AuthResponse 总结为一个新的组合对象,比如说 NewResponse 类并返回它。

    @Getter
    public class NewResponse extends MainResponse {
    
        @JsonProperty
        private AuthResponse response;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-11
      • 2014-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-12
      相关资源
      最近更新 更多