如果属性名称不等于字段名称,Jackson @JsonProperty 不起作用 [英] Jackson @JsonProperty not working if property name not equal field name
问题描述
我有以下 JSON
{
"known-name": "Zevs",
"approximate-age": 320
}
和绑定类
public class GodBinding {
@JsonProperty("known-name")
public String name;
@JsonProperty("approximate-age")
public int age;
// constructors
// getters & setters
}
并遵循 maven 依赖项2.23.22.5.4
And followng maven dependencies 2.23.2 2.5.4
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>${jersey.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>${jackson.version}</version>
</dependency>
</dependencies>
如果我发布这样的json,那么我会得到意想不到的结果,结果为空.
If I post such json then I have unexpected result with null's.
GodBinding [name=null, age=0]
如果我使用没有名称的@JsonProperty 并发送 JSON,其中属性名称等于字段名称
If I use @JsonProperty without names and send JSON where property names equal field names
{
"name": "Zevs",
"age": 320
}
然后它工作正常
GodBinding [name=Zevs, age=320]
如果有人知道,如何使字段上的@JsonProperty("name") 正常工作?
If somebody know, how to make @JsonProperty("name") on fields working correctly?
推荐答案
当Jackson 的注解是Jackson 1,而你想使用Jackson 2 时,经常会出现这种情况,很多其他问题都提到过.
This is often caused when the annotations of Jackson is of Jackson 1, but you want to use Jackson 2, as mentioned in many other questions.
就我而言,在项目中我有另一个错误导入的依赖项:
In my case, in the project I have another dependency which was imported wrongly:
import org.testcontainers.shaded.com.fasterxml.jackson.databind.ObjectMapper;
当我创建 ObjectMapper
时.我猜 testcontainers
使用它自己的 ObjectMapper
作为它的依赖并错误地暴露它;实际上它是一个旧版本.不确定哪个是.
when I create the ObjectMapper
. I guess testcontainers
uses its own ObjectMapper
as its dependency and exposed it incorrectly; actually it is an older version. Not sure which is.
我改成
import com.fasterxml.jackson.databind.ObjectMapper;
现在一切正常.这就是我所说的第一级依赖",而不是依赖的依赖".在我的 gradle 文件中,它是 2.3 版.
and all works now. This is what I call "first level dependency", not "dependency of dependency". In my gradle file it is version 2.3.
我提到这个是因为:
我看到其他问题只提到了 Jackson 1 和 2 之间的混淆,而不是
testcontainer
的这个.我们必须忽略那些不是fasterxml.jackson
的.
I see other questions only mentioning the confusion between Jackson 1 and 2, not this of
testcontainer
. We just must ignore those not offasterxml.jackson
.
不仅要注意@JsonProperty
等的版本,还要注意你在导入ObjectMapper
和反序列化功能
.
Pay attention of the version not only of @JsonProperty
, etc, but also the version of Jackson you use when importing ObjectMapper
and DeserializationFeature
.
这篇关于如果属性名称不等于字段名称,Jackson @JsonProperty 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!