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

查看:265
本文介绍了@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 ,具有正确的属性名称 fileName setFileName 有一个不同的 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天全站免登陆