杰克逊没有用@JsonProperty覆盖吸气剂

tt_*_*ntz 14 java getter serialization json jackson

JsonProperty不会覆盖杰克逊从getter获取的默认名称.如果我用ObjectMapper杰克逊和杰克森序列化下面的课程,我会得到

{"hi":"hello"}
Run Code Online (Sandbox Code Playgroud)

如您所见,JsonProperty注释无效

class JacksonTester {
    String hi;

    @JsonProperty("hello")
    public String getHi() {
        return hi;
    }
}   
Run Code Online (Sandbox Code Playgroud)

放置@JsonProperty字符串本身也不起作用.我似乎可以更改名称的唯一方法是重命名getter,唯一的问题是它的第一个字母总是小写

tt_*_*ntz 30

问题是我正在使用旧的和新的杰克逊库

即在我之前我必须 import org.codehaus.jackson.annotate.JsonProperty; 改变到下面,以便与我正在使用的库一致.

因为我使用maven也意味着更新我的maven依赖项. import com.fasterxml.jackson.annotation.JsonProperty;

为了它的工作,我需要在@JsonPropertygetter上的注释(把它放在对象上不起作用)

我在这里找到答案(感谢francescoforesti) @JsonProperty没有按预期工作

  • 我为此伤了一天!谢谢你 (2认同)

Fra*_* C. 21

如果使用 Kotlin

我知道最初的问题是在 Java 中,但由于 Kotlin 变得非常流行并且许多人可能正在使用它,我想在这里发布它以帮助其他人。

无论如何,对于 Kotlin,由于 getter/setter 的工作方式,如果您使用的是val,这意味着您只公开 getter,您可能需要将注释应用到 getter,如下所示:

class JacksonTester(@get:JsonProperty("hello") val hi: String)

Run Code Online (Sandbox Code Playgroud)

  • 这是 Java 和 Kotlin 之间非常重要的区别,也正是我所需要的。 (3认同)

Kha*_*led 8

我知道这是一个老问题,但是当我发现它与Gson库冲突时,对我来说我可以使用它,所以我不得不使用@SerializedName("name")而不是@JsonProperty("name")希望这会有所帮助


Dmi*_*y S 6

我有同样的问题

您只需替换 import com.fasterxml.jackson.annotation.JsonProperty; 导入 org.codehaus.jackson.annotate.JsonProperty;是工作。

  • 非常感谢。疯了吧 (2认同)

Xch*_*hai 5

从较早版本更新到FasterXML Jackson 2.8.3时遇到了这个问题。

问题在于,当将来自数据库的JSON响应反序列化为Java类对象时,我们的代码没有包含@JsonSetter在类的setter上。因此,在进行序列化时,输出没有利用类的getter将Java类对象序列化为JSON(因此@JsonProperty()装饰器未生效)。

我通过添加@JsonSetter("name-from-db")该属性的setter方法解决了该问题。

另外,@JsonProperty()可以使用并且应该使用@JsonGetter()更特定于重命名属性的方法,而不是使用getter方法重命名属性。

这是我们的代码:

public class KwdGroup {
    private String kwdGroupType;

    // Return "type" instead of "kwd-group-type" in REST API response
    @JsonGetter("type") // Can use @JsonProperty("type") as well
    public String getKwdGroupType() {
        return kwdTypeMap.get(kwdGroupType);
    }

    @JsonSetter("kwd-group-type") // "kwd-group-type" is what JSON from the DB API outputs for code to consume 
    public void setKwdGroupType(String kwdGroupType) {
        this.kwdGroupType = kwdGroupType;
    }
}
Run Code Online (Sandbox Code Playgroud)