本文介绍了强制GSON使用特定的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
public class UserAction {
private final UUID uuid;
private String userId;
/* more fields, setters and getters here */
public UserAction(){
this.uuid = UUID.fromString(new com.eaio.uuid.UUID().toString());
}
public UserAction(UUID uuid){
this.uuid = uuid;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final UserAction other = (UserAction) obj;
if (this.uuid != other.uuid && (this.uuid == null || !this.uuid.equals(other.uuid))) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 7;
hash = 53 * hash + (this.uuid != null ? this.uuid.hashCode() : 0);
return hash;
}
}
我使用Gson来串行化和反序列化这个类。如今天,我不得不在这个对象中添加最后一个UUID。我没有问题序列化。我需要强制gson在反序列化时使用 public UserAction(UUID uuid)
构造函数。
推荐答案
您可以实现自定义的并向GSON注册。
You could implement custom JsonDeserializer and register with GSON.
class UserActionDeserializer implements JsonDeserializer<UserAction>() {
public UserAction deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
return new UserAction(UUID.fromString(json.getAsString());
}
GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(UserAction.class, new UserActionDeserializer());
请注意,此代码尚未经过测试。
Bear in mind that this code has not been tested.
这篇关于强制GSON使用特定的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!