【发布时间】:2017-08-01 05:07:56
【问题描述】:
我有一个模型 RForm 需要使用 Java JSON 库 Jackson 进行序列化和反序列化。
当前RForm 型号为:
public class RForm implements Serializable {
private ArrayList<Element> pit;
private ArrayList<Element> match;
public RForm() {}
public RForm(ArrayList<Element> pit, ArrayList<Element> match) {
this.pit = pit;
this.match = match;
}
}
注意,我有两个包含Elements 的ArrayLists。 Element 是一个抽象类,有八个孩子,当它们被序列化时,Element 类中的一个对象可以是这八个孩子中的任何一个。我在尝试序列化和反序列化这些数组时遇到了一系列问题。这是要序列化的代码:ObjectMapper mapper = new ObjectMapper();String serialized = mapper.writeValueAsString(new RForm());
反序列化:
RForm form = mapper.readValue(serialized, RForm.class);
这是我得到的错误:
error occured: Unexpected token (END_OBJECT), expected FIELD_NAME: missing
property 'type' that is to contain type id (for class
com.cpjd.robluscouter.forms.elements.Element)
08-01 00:03:59.963 14143-14165/? I/System.out: at [Source:
java.io.StringReader@49aa883; line: 1, column: 186] (through reference
chain: com.cpjd.robluscouter.models.RForm["match"])
这是Element 类:
@Data
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include =
JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = EBoolean.class, name = "EBoolean"),
@JsonSubTypes.Type(value = ECheckbox.class, name = "ECheckbox"),
@JsonSubTypes.Type(value = EChooser.class, name = "EChooser"),
@JsonSubTypes.Type(value = ECounter.class, name = "ECounter"),
@JsonSubTypes.Type(value = EGallery.class, name = "EGallery"),
@JsonSubTypes.Type(value = ESlider.class, name = "ESlider"),
@JsonSubTypes.Type(value = ESTextfield.class, name = "ESTextfield"),
@JsonSubTypes.Type(value = EStopwatch.class, name = "EStopwatch"),
@JsonSubTypes.Type(value = ETextfield.class, name = "ETextfield")
})
public abstract class Element implements Serializable {
private String title;
private int ID;
private boolean modified; // if this is false, we can safely override this value
public Element() {}
Element(String title) {
this.title = title; modified = false;
}
public abstract String getSubtitle();
}
【问题讨论】:
-
您尝试反序列化的字符串是通过您的代码进行序列化的,还是来自其他地方?您是否检查过您的序列化字符串是否包含“类型”字段?
-
不,它是用上面显示的
ObjectMapper序列化的。它不包含类型字段。 @albert_nil
标签: java serialization jackson