java 超类值的 Jackson JSON 映射
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6681820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hymanson JSON mapping of superclass value
提问by Ralph
I am using Hymanson 1.8.3 in a Spring application to map Java Objects to JSON.
我在 Spring 应用程序中使用 Hymanson 1.8.3 将 Java 对象映射到 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.)
我的一个 Java 类 ( Child
) 扩展了Parent
作为 Libary 一部分的超类 ( ),因此我无法修改它。(特别是我无法添加注释。)
I am using @JsonAutoDetect(JsonMethod.NONE)
because I need only a small set of fields from the object, instead I am using @JsonProperty
.
我使用@JsonAutoDetect(JsonMethod.NONE)
是因为我只需要对象中的一小组字段,而不是我使用@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 Hymanson to pay attention to this field, without modifying the parent class (because I can not modify it).
但是我需要的字段之一是id
来自超类的字段,但是我不知道如何告诉Hymanson关注这个字段,而不修改父类(因为我无法修改它)。
回答by Nicolae Albu
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.
如果将注释放在 getter 上(而不是直接放在字段上),则可以覆盖该getId()
方法(如果它不是超类中的 final)并向其添加注释。
class Parent {
public long getId(){...};
...
}
@JsonAutoDetect(JsonMethod.NONE)
class Child extends Parent {
private String title;
@JsonProperty
public String getTitle() {...}
@Override
@JsonProperty
public long getId() {
return super.getId();
}
}
回答by Programmer Bruce
I am not able to add annotations
我无法添加注释
You can add annotations using mix-ins. See http://wiki.fasterxml.com/HymansonMixInAnnotationsfor details.
您可以使用混合来添加注释。有关详细信息,请参阅http://wiki.fasterxml.com/HymansonMixInAnnotations。
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.
根据类字段/方法结构的其余部分,另一种可能有效的方法是通过 ObjectMapper 配置字段/方法的可见性访问。下面一行演示了如何进行这样的配置,不一定是你需要的具体配置。
mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY));
I am using @JsonAutoDetect(JsonMethod.NONE) because I need only a small set of fields from the object, instead I am using @JsonProperty
我使用 @JsonAutoDetect(JsonMethod.NONE) 因为我只需要来自对象的一小部分字段,而不是我使用 @JsonProperty
I should have realized that was possible. I have to update my blog post. Thank you.
我应该意识到这是可能的。我必须更新我的博客文章。谢谢你。