0
我有一個需要使用Java JSON庫Jackson
進行序列化和反序列化的模型RForm
。用Jackson正確序列化和反序列化Java類
目前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
是一個抽象類,有8個孩子,當這些孩子被序列化時,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:
[email protected]; 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();
}
個
您嘗試反序列化的字符串是否通過您的代碼進行了序列化,還是來自其他地方?你有沒有檢查過你的序列化字符串是否包含「type」字段? –
不,它是用上面顯示的ObjectMapper進行序列化的。它不包含類型字段。 @albert_nil – wdavies973