java接口反序列化

2vuwiymt  于 2021-07-07  发布在  Java
关注(0)|答案(1)|浏览(416)

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

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中搜索operation字段,这当然是空的,因为operation字段总是存在于父级中,并且父级有response->authresponse->createacassponse等等

nwlqm0z1

nwlqm0z11#

我想张贴一个解决方案,希望能帮助你。
如果对象中的某个对象总是返回不同的属性,则可以使用以下方法:
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需要response json属性,我们就必须创建一个额外的类来扩展抽象类,这意味着我们将有需要ireresponse作为返回的getresponse,因此我们在authresponse中实现了这个接口,我们可以简单地将authresponse归纳为一个新的(比如说newresponse)类中的组合对象并返回它。

@Getter
public class NewResponse extends MainResponse {

    @JsonProperty
    private AuthResponse response;
}

相关问题