I'm trying to serialize a class that has a list of interface objects. I have added a type register that should get it to work, however I'm out of luck as it's still not working. Code below.
Rule:
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);
}
One of the ActionRule classes:
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;
}
}
And finally, the class that must be serialized & deserialized:
public class RuleList {
List<Rule> rules = new ArrayList<Rule>();
}
All of this should work with my type adapter:
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;
}
}
}
Could someone PLEASE point out what I'm doing wrong? Error I'm receiving:
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.
The GSON deserializer needs a default constructor on the class being deserialized, ie RuleList
.
If you can't provide a default constructor then you need to register an InstanceCreator
that will provide a new RuleList to the deserializer.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.