简体   繁体   English

Jackson 使用不同的字段名称进行反序列化和序列化

[英]Jackson Deserialize and Serialize with different field name

I have a class that I want to deserialize and serialize with Jackson.我有一个 class,我想用 Jackson 反序列化和序列化。 Currently this is what I have目前这就是我所拥有的

class Person {
    @JsonAlias("fullName")
    @JsonDeserialize(using = NameDeserializer.class)
    String name;
}

I want to be able to read from {"fullName": "John Doe"} and write to {"name": "John Doe"} .我希望能够读取{"fullName": "John Doe"}并写入{"name": "John Doe"}

I am also using Lombok to create setter and getter, so I could not use @JsonProperty on method level.我也在使用 Lombok 创建 setter 和 getter,所以我不能在方法级别使用 @JsonProperty。 Any idea how would I approach this, because currently it seems like the @JsonAlias is not working as expected.知道我将如何处理这个问题,因为目前看来@JsonAlias 似乎没有按预期工作。 I'm using Jackson 2.10 to map object.我正在使用 Jackson 2.10 到 map object。

EDIT编辑

Turns out using Alias works just fine.事实证明,使用 Alias 效果很好。 Though in figuring out how it didn't work the first time, I override lombok setter虽然在第一次弄清楚它是如何不起作用的时,我覆盖了 lombok setter

@JsonProperty("firstName")
public void setName(String name){
    this.name = name;
}

From here I found out that my Deserializer is actually the problem.从这里我发现我的反序列化器实际上是问题所在。

Just remove the custom deserializer, and annotate the field with @JsonProperty , which should make your scenario work:只需删除自定义反序列化器,并使用@JsonProperty注释该字段,这将使您的方案工作:

class Person {
    @JsonAlias("fullName")
    @JsonProperty
    String name;
}

The custom deserializer controls how the deserialization is done, and this is where the alias is probably being ignored.自定义反序列化器控制反序列化的完成方式,这就是别名可能被忽略的地方。

you can use JsonProperty annotation with properties as it is written here https://github.com/FasterXML/jackson-annotations您可以将 JsonProperty 注释与属性一起使用,因为它写在这里https://github.com/FasterXML/jackson-annotations

public class Name {
    @JsonProperty("firstName")
    public String _first_name;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM