我有一个模型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;
}
}
注意,我有两个ArrayLists
,其中包含Elements
。 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();
}