我做一个复制机制,我同步两个数据库。为了在数据库之间进行通信,我使用Gson将对象序列化为JSON。每个对象都有一个UUID来标识它。为了避免必须发送最新的项目,当对象包含在要复制的对象的字段中时,我使用对象UUID。仅在字段上使用自定义解串器?
我们得到了以下类:
public class Entity {
String uuid;
// Getters and setters..
}
public class Article extends Entity {
String name;
Brand brand;
// Getters and setters..
}
public class Brand extens Entity {
String name;
Producer producer
// Getters and setters..
}
public class Producer extends Entity {
String name;
// Getters and setters..
}
如果我连载文章JSON表示将看起来像这样:
{"brand":"BrandÖ179d7798-aa63-4dd2-8ff6-885534f99e77","uuid":"5dbce9aa-4129-41b6-a8e5-d3c030279e82","name":"Sun-Maid"}
其中 “BrandÖ179d7798-aa63-4dd2-8ff6-885534f99e77” 是班级(“品牌”)和UUID。
如果我序列品牌我想到:
{"producer":"ProducerÖ173d7798-aa63-4dd2-8ff6-885534f84732","uuid":"5dbce9aa-4129-41b6-a8e5-d3c0302w34w2","name":"Carro"}
在杰克逊我会改变文章类:
public class Article {
String uuid;
String name;
@JsonDeserialize (using = EntityUUIDDeserializer.class) @ JsonSerialize (using = EntityUUIDSerializer.class)
Brand brand;
// Getters and setters..
}
,并实现自定义的串行器和解串返回UUID,而不是对象。
Gson没有@JsonDeserialize注释。
如果我们安装串行器和解串做这样的:
Gson gson = new GsonBuilder()
.registerTypeAdapter(Producer.class, new EntityUUIDDeserializer())
.registerTypeAdapter(Brand.class, new EntityUUIDDeserializer())
.registerTypeAdapter/Producer.class, new EntityUUIDSerializer())
.registerTypeAdapter(Brand.class, new EntityUUIDSerializer())
.create();
我们可以连载文章和品牌确定。通过
Article article= gson.fromJson(inputJSONString, Article.class);
反序列化第二十工作正常,但
Brand brand= gson.fromJson(inputJSONString, Brand.class);
不起作用。我猜测是,当我们反序列化一个品牌时,我们得到了Brand的反序列化器,试图返回一个UUID字符串,但我们希望反序列化器返回一个品牌对象。
有没有办法避免创建两个不同的Gson对象?两个不同的Gson对象的问题是,当你想要反序列化包含Article和Brand的对象时。
如果我们仅序列化包含实体的实体,则您的解决方案可以正常工作。但是,如果我们有一个包含Brand对象的Article对象,它将不起作用。我们有任何解决方案的用例? 对不起,我的可怜的代码示例导致你错过了。 – 2013-03-12 13:54:38
为什么它不工作?您为特定的类注册一个序列化器/反序列化器。遇到该类时,就会使用它们。在你编辑的案例中,你会注册他们的品牌。class'。这与你在杰克逊使用的注释类似,只是它在全球范围内。 – 2013-03-12 15:05:37
你的权利又一次,我再次解释这个问题不好。请看看我的问题的变化。 – 2013-03-12 19:35:53