字段上的@JsonProperty 注释以及 getter/setter [英] @JsonProperty annotation on field as well as getter/setter

查看:26
本文介绍了字段上的@JsonProperty 注释以及 getter/setter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我继承了某个位代码,该代码在 getter/setter 上带有 @JsonProperty 注释.目的是当使用 Jackson 库序列化对象时,字段具有该特定名称.

I have inherited a certain bit code that has the @JsonProperty annotation on getter/setters. The purpose is so that when the object is serialized using the Jackson library, the fields have that specific name.

当前代码:

private String fileName;

@JsonProperty("FILENAME")
public String getFileName()
{
    return fileName;
}

@JsonProperty("FILENAME")
public void setFileName(String fileName)
{
    this.fileName = fileName;
}

现在对于另一个工具,我还需要使用 JsonProperty 注释该字段.所以这将是我更改的代码:

Now for another tool, I need to annotate the field with JsonProperty as well. So this will be my changed code:

@JsonProperty("FILENAME")
private String fileName;

@JsonProperty("FILENAME")
public String getFileName()
{
    return fileName;
}

@JsonProperty("FILENAME")
public void setFileName(String fileName)
{
    this.fileName = fileName;
}

有没有人在字段和 getter/setter 上使用过相同的注释?我在网上环顾四周,但什么也没看到.

Has anyone used this same annotation on both - the field as well as the getter/setters? I looked around on the net but didn't see anything.

我已经编译 &运行代码,但我不确定这是否会导致任何问题.对此有什么想法吗?

I have compiled & run the code but I'm not sure if this would this cause any problems down the road. Any thoughts on this?

推荐答案

我基于一些测试的观察结果是,与属性名称不同的名称生效:

My observations based on a few tests has been that whichever name differs from the property name is one which takes effect:

例如.考虑对您的案例稍作修改:

For eg. consider a slight modification of your case:

@JsonProperty("fileName")
private String fileName;

@JsonProperty("fileName")
public String getFileName()
{
    return fileName;
}

@JsonProperty("fileName1")
public void setFileName(String fileName)
{
    this.fileName = fileName;
}

fileName 字段和方法 getFileName 都有正确的属性名称 fileNamesetFileName不同的 fileName1,在这种情况下,Jackson 将在反序列化时在 json 中查找 fileName1 属性,并在以下位置创建一个名为 fileName1 的属性序列化的要点.

Both fileName field, and method getFileName, have the correct property name of fileName and setFileName has a different one fileName1, in this case Jackson will look for a fileName1 attribute in json at the point of deserialization and will create a attribute called fileName1 at the point of serialization.

现在,谈到您的情况,所有三个@JsonProperty 都与 fileName 的默认属性名称不同,它只会选择其中一个作为属性(FILENAME),如果三个中的任何一个不同,它就会抛出异常:

Now, coming to your case, where all the three @JsonProperty differ from the default propertyname of fileName, it would just pick one of them as the attribute(FILENAME), and had any on of the three differed, it would have thrown an exception:

java.lang.IllegalStateException: Conflicting property name definitions

这篇关于字段上的@JsonProperty 注释以及 getter/setter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆