超类值的 Jackson JSON 映射
我在 Spring 应用程序中使用 Jackson 1.8.3 将 Java 对象映射到 JSON。
我的一个 Java 类 (Child
) 扩展了一个属于库一部分的超类 (Parent
),因此我无法修改它。 (特别是我无法添加注释。)
我使用 @JsonAutoDetect(JsonMethod.NONE)
因为我只需要对象中的一小组字段,而是使用 @JsonProperty
。
class Parent {
public long getId(){...};
...
}
@JsonAutoDetect(JsonMethod.NONE)
class Child extends Parent {
@JsonProperty
private String title;
}
但是我需要的字段之一是来自超类的字段id
,但我不知道如何告诉Jackson注意这个字段,而不修改父类(因为我无法修改)。
I am using Jackson 1.8.3 in a Spring application to map Java Objects to JSON.
One of my Java Class (Child
) extends an super class (Parent
) that is part of an Libary, so I am not able to modify it. (Especially I am not able to add annotations.)
I am using @JsonAutoDetect(JsonMethod.NONE)
because I need only a small set of fields from the object, instead I am using @JsonProperty
.
class Parent {
public long getId(){...};
...
}
@JsonAutoDetect(JsonMethod.NONE)
class Child extends Parent {
@JsonProperty
private String title;
}
But one of the fields I need is an field id
from the superclass, but I don't know how to tell Jackson to pay attention to this field, without modifying the parent class (because I can not modify it).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果将注释放在 getter 上(而不是直接放在字段上),则可以重写
getId()
方法(如果它在超类中不是最终方法)并向其添加注释。If you put the annotations on the getters (instead directly on the fields), you can override the
getId()
method (if it's not final in the superclass) and add an annotation to it.您可以使用混合添加注释。有关详细信息,请参阅 http://wiki.fasterxml.com/JacksonMixInAnnotations。
根据类字段/方法结构的其余部分,另一种可能有效的方法是通过 ObjectMapper 配置字段/方法的可见性访问。下面一行演示了如何进行这样的配置,不一定是您需要的具体配置。
我应该意识到这是可能的。我必须更新我的博客文章。谢谢。
You can add annotations using mix-ins. See http://wiki.fasterxml.com/JacksonMixInAnnotations for details.
Depending on what the rest of the class feild/method structures are, another approach that might work would be to configure visibility access of fields/methods through ObjectMapper. The following line demonstrates how to make such a configuration, not necessarily the specific configuration you need.
I should have realized that was possible. I have to update my blog post. Thank you.