2013-05-08 59 views
0

在任何时间点,我将只设置一个setter方法,但JsonProperty名称应该相同。当我编译这个时,我得到一个异常。如何为两者设置相同的名称。?如何使用相同的@jsonproperty名称int以下示例?

public String getType() { 
    return type; 
} 

@JsonProperty("Json") 
public void setType(String type) { 
    this.type = type; 
} 

public List<TwoDArrayItem> getItems() { 
    return items; 
} 

@JsonProperty("Json") 
public void setItems(List<TwoDArrayItem> items) { 
    this.items = items; 
} 
+0

为什么你隐瞒编译器错误的细节?这将是相关的,除非你喜欢猜测游戏。 – 2013-05-08 05:27:35

+0

那么你期望杰克逊在任何时候知道要序列化哪一个?毕竟,'null'是一个完美的序列化值。 – 2013-05-08 05:29:20

+0

我得到这个例外。 com.fasterxml.jackson.databind.JsonMappingException:属性“Json”的getter定义冲突:在两个setter方法中,一个在时间上是空的。 – Naveen 2013-05-08 05:34:49

回答

1

杰克逊倾向于支持常见场景和良好的设计选择以支持注释。

您的情况代表一种非常罕见的情况。你有一个领域在不同的环境中有两个不同的含义。通常情况下,这不会是一种有利的数据格式,因为它在另一端为消费者增加了凌乱的逻辑......他们需要在每种情况下都能够理解“Json”属性的含义。如果您只使用了两个不同的属性名称,它对于消费者来说会更清洁。那么简单地检查每个财产的存在就足以知道它获得了哪个替代方案。

您的Java类似乎设计不佳。类不应该有这种类型的上下文或模式,在一个上下文中允许一个字段,但在另一个上下文中不是。

因为这主要是与你的设计的味道,而不是串行化的逻辑,最好的办法可能会纠正你的Java类层次结构:

class BaseClass { 
} 

class SubClassWithItems { 
    public List<TwoDArrayItem> getItems() { 
     return items; 
    } 

    @JsonProperty("Json") 
    public void setItems(List<TwoDArrayItem> items) { 
     this.items = items; 
    } 
} 

class SubClassWithType { 
    public String getType() { 
     return type; 
    } 

    @JsonProperty("Json") 
    public void setType(String type) { 
     this.type = type; 
    } 
} 

这样,你的类没有一组不同的字段基于某些运行时状态。如果运行时状态正在驱动您的类包含的字段,那么与仅使用Map相比,这不会更好。

如果你不能改变这一点,你只剩下custom serialization

相关问题