无法将json响应Map到对象,因为存在多个实现

r6hnlfcb  于 2021-07-13  发布在  Java
关注(0)|答案(0)|浏览(216)

我有这样的班级结构:
responsebody.java文件:

public class ResponseBody {
    private String type;
    private A a;

    public static class A {
        private List<B> b;
    }
}

b、 java 语:

public class B {
    private String c;
    private DynamicJson dynamicJson;
}

dynamicjson.java文件:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, 
      include = As.PROPERTY, property = "type")
@JsonSubTypes({
        @JsonSubTypes.Type(value = Child1.class, name = "child-1"),
        @JsonSubTypes.Type(value = Child2.class, name = "child-2"),
        @JsonSubTypes.Type(value = Child3.class, name = "child-3")
})
public abstract class DynamicJson {
    private String onlyKnownField;
}

儿童1.java

@JsonTypeName("child-1")
public class Child1 extends DynamicJson {

// Number of fields and field names here change based on which implementation of Dynamic Json

}

同样,child2和child3类。
移除了构造函数、setter、getter。
我想在json下面强制转换/反序列化 ResponseBody.java 班级。

{
    "type": "child-1",
    "a": {
        "b": [
            {
                "c": "guid",
                "dynamicJson": {
                    "onlyKnownField": "guid", // only field that always comes
                    /*
                    dynamic number of fields based on "type", say 2 fields, if type is                                                                         
                    something else then number of fields here is different
                    */
                }
            }
        ]
    }
}

根据“type”值,“dynamicjson”字段可以有不同数量的字段,其中包含不同的名称。这似乎是问题所在,
这是正在使用的代码:

ObjectMapper objectMapper = new ObjectMapper();
ResponseBody responseBody = objectMapper.readValue(json.getBody(), ResponseBody.class);

但是,上面的代码给出了以下错误:

Missing type id when trying to resolve subtype of [simple type, class DynamicJson]

我做错什么了?
如果需要其他信息,请告诉我。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题