仅在字段上使用自定义反序列化程序?

时间:2013-03-10 18:01:27

标签: gson

我执行复制机制,我同步两个数据库。为了在数据库之间进行通信,我使用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”是类(“Brand”)和UUID。

如果我序列化我想要的品牌:

{"producer":"ProducerÖ173d7798-aa63-4dd2-8ff6-885534f84732","uuid":"5dbce9aa-4129-41b6-a8e5-d3c0302w34w2","name":"Carro"}

在杰克逊,我会将Article class更改为:

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-object。

有没有办法避免创建两个不同的Gson对象?两个不同的Gson对象的问题是当您想要反序列化包含Article和Brand的对象时。

1 个答案:

答案 0 :(得分:1)

您编写序列化器/解串器并将其注册到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字段。

相关问题