![](/img/trans.png)
[英]How to remake bidirectional mappings when deserializing JSON using Gson?
[英]How to initialize PropertyChangeSupport when deserializing from JSON (Gson)?
我的對象實現了PropertyChangeSupport
,但是當我從json字符串反序列化時,盡管我使用默認構造函數中的new PropertyChangeSupport(this)
初始化了值,但變量propertyChangeSupport
將為null
。 如何使用Gson正確初始化或反序列化它?
說我有這個對象:
public class Blah implements BlahInterface {
private PropertyChangeSupport propertyChangeSupport;
protected int id;
protected BlahType type;
public Blah() {
propertyChangeSupport = new PropertyChangeSupport(this);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public BlahType getType() {
return type;
}
public void setType(BlahType type) {
this.type = type;
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
this.propertyChangeSupport.addPropertyChangeListener(listener);
}
public PropertyChangeListener[] getPropertyChangeListeners() {
return this.propertyChangeSupport.getPropertyChangeListeners();
}
}
我還嘗試過放置new PropertyChangeSupport(this);
直接在開始,也不走。 我想要避免手動創建諸如initializePropertyChangeSupport()
類的函數,然后在反序列化之后手動調用它,因為這有點丑陋。
我正在嘗試做的是:
JsonArray ja = json.get("blahs").getAsJsonArray();
ja.forEach(item -> {
Blah blah = BlahInterface.Parse(item.toString());
// But here I can't addPropertyChangeListener because propertyChangeSupport is null
// vvvvvvvvvvvv
blah.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
BlahState state = (BlahState) evt.getNewValue();
Logger.debug("Property had been updated, " + state.toString());
}
});
});
這是我的json解析函數:
@SuppressWarnings("unchecked")
public static <T extends Blah> T Parse(String json) {
Gson gson = new Gson();
Blah t = new Blah(gson.fromJson(json, Blah.class));
switch (t.getType()) {
case blahone:
return (T) gson.fromJson(json, BlahOne.class);
default:
return (T) t;
}
};
解決此問題的方法是在我的對象中實現InstanceCreator<T>
。 這樣,當Gson嘗試反序列化對象時,它將調用createInstance
函數,該函數又返回初始化了PropertyChangeSupport
變量的正確對象。 下面的示例代碼:
public class Blah implements InstanceCreator<Blah> {
private final transient PropertyChangeSupport pcs = new PropertyChangeSupport(this);
...
public void addPropertyChangeListener(PropertyChangeListener listener) {
this.pcs.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
this.pcs.removePropertyChangeListener(listener);
}
@Override
public Blah createInstance(Type type) {
return new Blah();
}
}
注意: pcs
僅存在transient關鍵字,因此Gson會在序列化期間跳過它,否則Gson會引發異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.