将字符串反序列化为对象 ..ObjectMapper objectMapper = new ObjectMapper();objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);System.out.println(json); // Output is belowStatus status = new ObjectMapper().readValue(json, Status.class);ProcessingStage s = (ProcessingStage) status.getStages().get(0);// orDataStage s = (DataStage) status.getStages().get(0);产生这些错误..java.lang.ClassCastException: Stage cannot be cast to ProcessingStagejava.lang.ClassCastException: Stage cannot be cast to DataStage我如何使用 Jackson 将 的子类反序列Stage化为正确的实例类型?我期待status.stages包含:[DataStage, DataStage, ProcessingStage],但看起来它包含:[Stage, Stage, Stage]。上面的输出System.out.println(json);..{ "stages": [ { "name":"Pre", "order":1, "data": [ { "id":"0688709c-17be-472a-bf5e-7d7b11bd8ccf" } ], }, { "name":"Processing", "order":2, "data": [ { "id":"ac3ecbb5-2aa6-4faf-b443-391472065219" } ], }, { "name":"Post", "order":3, "status":"not-started" } ]}Status.javaimport java.util.List;import com.fasterxml.jackson.annotation.JsonProperty;public class Status { @JsonProperty("stages") private List<Stage> stages; public Status() {} public List<Stage> getStages() { return stages; } public void setStages(List<Stage> stages) { this.stages = stages; }}Stage.javaimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;import com.fasterxml.jackson.annotation.JsonProperty;import com.fasterxml.jackson.annotation.JsonSubTypes;@JsonIgnoreProperties(ignoreUnknown = true)@JsonSubTypes({ @JsonSubTypes.Type(value = ProcessingStage.class, name = "ProcessingStage"), @JsonSubTypes.Type(value = DataStage.class, name = "DataStage") })
1 回答
手掌心
TA贡献1942条经验 获得超3个赞
您可以尝试先使用 instanceOf 评估对象的类
if(status.getStages().get(0) instanceOf ProcessingStage) {
ProcessingStage s = (ProcessingStage) status.getStages().get(0);
}
或评估其他班级
DataStage
添加回答
举报
0/150
提交
取消