gpt4 book ai didi

java - 阻止 jackson 改变变量名的大小写

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:38:07 25 4
gpt4 key购买 nike

我在 Spring 中使用 Jackson 将我的类序列化为 JSON。当我像下面的示例那样序列化一个类时,Jackson 正在将某些字段的名称从 Camel Case 更改为小写。我知道我可以通过创建自定义(反)序列化器来解决这个问题,但我希望在全局范围内关闭它。也许通过在 application.properties 中设置一个属性。

根据 default Jackson naming strategy ,这是不应该发生的:

In absence of a registered custom strategy, default Java property naming strategy is used, which leaves field names as is...

class Foo {
private final String firstName;
private final String aName;
private final String name;
private final String abName;

Foo(final String firstName, final String aName, final String name, final String abName) {
this.firstName = firstName;
this.aName = aName;
this.name = name;
this.abName = abName;
}
// Getters here
}

public static void main(String[] args) {
final ObjectMapper mapper = new ObjectMapper();
final Foo foo = new Foo("first", "a", "name", "ab");
final String jsonInString = mapper.writeValueAsString(foo);
System.out.println(jsonInString);
}

预期:

{"firstName":"first","name":"name","abName":"ab","aName":"a"

实际:

{"firstName":"first","name":"name","abName":"ab","aname":"a"

编辑:

将问题缩小到对 setter/getter 的解释。开始看起来像 Jackson 中的一个错误。

class Foo {
private final String aName;

Foo(final String aName) {
this.aName = aName;
}

public String getaName() {
return this.aName;
}
}

序列化为 {"aName":"a"}

但是,

class Foo {
private final String aName;

Foo(final String aName) {
this.aName = aName;
}

public String getAName() {
return this.aName;
}
}

序列化为 {"aname":"a"}

最佳答案

这里的问题更多的是关于JavaBeans(TM) Specification .根据规范(第 58 页)

However to support the occasional use of all upper-case names, we check if the first two characters of the name are both upper case and if so leave it alone

“FooBah” becomes “fooBah”

“Z” becomes “z”

“URL” becomes “URL”

并且您有一个带有 aName 字段的边缘案例。因为如果 getter 看起来像 AName() ,那么当您从这个 getter 转换回来时,您应该根据规范查找 AName 字段。这是附加信息 explanation

因此,要解决此问题,您可以在字段/getter 上方使用适当的 getter(getaName()) 或 @JsonProperty("aName") 注释

这里是 similar question

关于java - 阻止 jackson 改变变量名的大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46652019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com