我使用同步两个数据库的复制机制。为了在数据库之间进行通信,我使用 Gson 将对象序列化为 JSON。每个对象都有一个 UUID 来标识它。为了避免必须发送最新的项目,当对象包含在要复制的对象的字段中时,我使用对象 UUID。
我们有以下类(class):
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"}
在 jackson ,我会将 Article 类更改为:
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 时,我们会让 Brand 的反序列化器尝试返回 UUID 字符串,但我们希望反序列化器返回一个 Brand 对象。
有没有办法避免创建两个不同的 Gson 对象?两个不同的 Gson 对象的问题是当您想要反序列化同时包含 Article 和 Brand 的对象时。
最佳答案
您编写序列化器/反序列化器并将其注册到 Gson(使用 GsonBuilder
)。
https://sites.google.com/site/gson/gson-user-guide#TOC-Custom-Serialization-and-Deserialization
Gson g = new GsonBuilder()
.registerTypeAdapter(Producer.class, new MyProducerDeserializer())
.registerTypeAdapter(Producer.class, new MyProducerSerializer())
.create();
当您序列化/反序列化您的 Brand
类时,它将使用它们作为其中包含的 Producer
字段。
关于gson - 仅在字段上使用自定义反序列化器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15325597/