2017-08-01 110 views
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包含ElementsElement是一個抽象類,有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(); 

} 
+0

您嘗試反序列化的字符串是否通過您的代碼進行了序列化,還是來自其他地方?你有沒有檢查過你的序列化字符串是否包含「type」字段? –

+0

不,它是用上面顯示的ObjectMapper進行序列化的。它不包含類型字段。 @albert_nil – wdavies973

回答

0

步驟共同解決了這一問題:

  • 確保任何內部類是static,或最好,只是把他們在自己的類
  • 添加默認的構造函數,以每類
  • 上面添加註釋每個類
  • 告訴ObjectMapper忽略任何變量,它無法找到
  • 確保每一個變量有一個getter和一個setter(我使用的龍目島,所以這是罰款)
相關問題