我正在尝试序列化一个包含接口对象列表的类。我已经添加了一个类型寄存器,应该让它工作,但是我运气不好,因为它仍然没有工作。代码如下。
规则:
public interface Rule extends Serializable {
public String getName();
public boolean setData(String data);
public String getData();
}
RuleAbstract:
public abstract class RuleAbstract implements Rule {
private static transient final long serialVersionUID = 1L;
public RuleAbstract(){ }
}
ActionRule:
public interface ActionRule extends Rule {
public void doAction(Player player);
}
其中一个ActionRule类:
public class DoCmd extends RuleAbstract implements ActionRule {
private static transient final long serialVersionUID = 1L;
private static DoCmd i = new DoCmd();
public static DoCmd get() { return i; }
private String cmd;
public DoCmd(){
}
@Override
public void doAction(Player player) {
if(this.cmd == null) return;
MixinCommand.get().dispatchCommand(player, this.cmd);
}
@Override
public boolean setData(String data) {
/** Must start with leading slash */
if(!data.startsWith("/")) return false;
this.cmd = data;
return true;
}
@Override
public String getData() {
return this.cmd;
}
}
最后,必须序列化的班级&反序列化:
public class RuleList {
List<Rule> rules = new ArrayList<Rule>();
}
所有这一切都适用于我的类型适配器:
public class AdapterRule implements JsonDeserializer<Rule>, JsonSerializer<Rule> {
private static AdapterRule i = new AdapterRule();
public static AdapterRule get() { return i; }
@Override
public JsonElement serialize(Rule src, Type typeOf, JsonSerializationContext context) {
if(src.getData() != null || src.getData() != ""){
return new JsonPrimitive(String.format("%s %s", src.getName(), src.getData()));
}
return new JsonPrimitive(src.getName());
}
@Override
public Rule deserialize(JsonElement src, Type typeOf, JsonDeserializationContext context) throws JsonParseException {
String splitted[] = src.getAsJsonPrimitive().getAsString().split(" ");
if(splitted.length == 1){
return RuleAbstract.getRule(splitted[0]);
} else {
String tempData = "";
for(String data : splitted){
tempData = tempData + " " + data;
}
Rule rule = RuleAbstract.getRule(splitted[0]);
rule.setData(tempData);
return rule;
}
}
}
有人可以指出我做错了什么吗?我收到错误:
java.lang.RuntimeException: Unable to invoke no-args constructor for interface some.package.Rule. Register an InstanceCreator with Gson for this type may fix this problem.
答案 0 :(得分:0)
GSON反序列化器需要在反序列化的类上使用默认构造函数,即RuleList
。
如果您不能提供默认构造函数,那么您需要注册一个InstanceCreator
,它将为解串器提供一个新的RuleList。