使用Jackson正确地序列化和反序列化Java类

时间:2017-08-01 05:07:56

标签: java serialization jackson

我有一个模型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,其中包含ElementsElement是一个抽象类,有八个子节点,当序列化它们时,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();

}

0 个答案:

没有答案