Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
全局更改JSON属性_Json_Jackson_Jersey 2.0 - Fatal编程技术网

全局更改JSON属性

全局更改JSON属性,json,jackson,jersey-2.0,Json,Jackson,Jersey 2.0,我有一个场景,如果POJO中有一个XML属性(定义为@xmldattribute),那么它在JSON输出中的命名应该不同 @XmlAttribute(name = "value") //@JsonProperty("value-new") protected String value; 现在我可以使用@JsonProperty来定义新名称。但是我在每个POJO中都有很多这样的属性,并且在最后对所有这些属性(比如add-new)进行名称更改是“常见的”。是否可以在全球范围内执行此操作?您可以实现

我有一个场景,如果POJO中有一个XML属性(定义为
@xmldattribute
),那么它在JSON输出中的命名应该不同

@XmlAttribute(name = "value")
//@JsonProperty("value-new")
protected String value;

现在我可以使用
@JsonProperty
来定义新名称。但是我在每个POJO中都有很多这样的属性,并且在最后对所有这些属性(比如add-new)进行名称更改是“常见的”。是否可以在全球范围内执行此操作?

您可以实现自己的
属性名称策略

class XmlAttributePropertyNamingStrategy extends PropertyNamingStrategy {

    @Override
    public String nameForField(MapperConfig<?> config, AnnotatedField field, String defaultName) {
        XmlAttribute annotation = field.getAnnotation(XmlAttribute.class);
        if (annotation != null) {
            return defaultName + "-new";
        }
        return super.nameForField(config, field, defaultName);
    }
}
因为
xmldattribute
注释在字段级别可用,所以我们需要启用字段可见性并禁用getter。对于以下
POJO

class Pojo {

    @XmlAttribute
    private String attr = "Attr";
    private String value = "Value";
    // getters, setters
}
上面的示例打印:

{"attr-new":"Attr","value":"Value"}

谢谢我想通过JSonserialization实现这个想法,但这看起来更简单。此外,还必须启用功能
MapperFeature.ALLOW\u EXPLICIT\u PROPERTY\u RENAMING)
if字段显式命名才能使其工作。
{"attr-new":"Attr","value":"Value"}