是否可能:在类中有一个字段,但在Jackson库中序列化/反序列化期间为它取不同的名称?

例如,我有一个类“coordindiantes”。

class Coordinates{
  int red;
}

对于JSON的反序列化,希望有这样的格式:

{
  "red":12
}

但是当我序列化对象时,结果应该是这样的:

{
  "r":12
}

我试图通过在getter和setter上应用@JsonProperty注释来实现这一点(具有不同的值):

class Coordiantes{
    int red;

    @JsonProperty("r")
    public byte getRed() {
      return red;
    }

    @JsonProperty("red")
    public void setRed(byte red) {
      this.red = red;
    }
}

但我有个例外:

org.codehaus.jackson。map。exx . unrecognizedpropertyexception:无法识别的字段“red”


当前回答

您可以组合使用@JsonSetter和@JsonGetter来分别控制属性的反序列化和序列化。这也将允许您保持标准化的getter和setter方法名,它们与您实际的字段名相对应。

import com.fasterxml.jackson.annotation.JsonSetter;    
import com.fasterxml.jackson.annotation.JsonGetter;

class Coordinates {
    private int red;

    //# Used during serialization
    @JsonGetter("r")
    public int getRed() {
        return red;
    }

    //# Used during deserialization
    @JsonSetter("red")
    public void setRed(int red) {
        this.red = red;
    }
}

编辑:更新了文档链接,因为fastxmlgithub页面现在返回404。

其他回答

对于Kotlin的人:

data class TestClassDTO(
    @JsonProperty("user_name")
    val username: String
)

你将成功地从RestControllers中的POST有效载荷处理{"user_name": "John"}

但是当您需要用相同的@JsonProperty名称进行序列化时,您可以使用这种反射方法

fun Any.forceSerialize(separator: String, sorted: Boolean = false): String {
    var fieldNameToAnnotatedNameMap = this.javaClass.declaredFields.map { it.name }.associateWith { fieldName ->
        val jsonFieldName =
            this::class.primaryConstructor?.parameters?.first { it.name == fieldName }?.annotations?.firstOrNull { it is JsonProperty }
        val serializedName = if (jsonFieldName != null) (jsonFieldName as JsonProperty).value else fieldName
        serializedName
    }
    if (sorted)
        fieldNameToAnnotatedNameMap = fieldNameToAnnotatedNameMap.toList().sortedBy { (_, value) -> value}.toMap()
    return fieldNameToAnnotatedNameMap.entries.joinToString(separator) { e ->
        val field = this::class.memberProperties.first { it.name == e.key }
        "${e.value}=${field.javaGetter?.invoke(this)}"
    }
}

这并不是我所期望的解决方案(尽管这是一个合理的用例)。我的要求是允许一个存在bug的客户端(一个已经发布的移动应用程序)使用替代名称。

解决方案在于提供一个单独的setter方法,如下所示:

@JsonSetter( "r" )
public void alternateSetRed( byte red ) {
    this.red = red;
}

我将两个不同的getter /setter对绑定到一个变量:

class Coordinates{
    int red;

    @JsonProperty("red")
    public byte getRed() {
      return red;
    }

    public void setRed(byte red) {
      this.red = red;
    }

    @JsonProperty("r")
    public byte getR() {
      return red;
    }

    public void setR(byte red) {
      this.red = red;
    }
}

在属性上同时使用JsonAlias和JsonProperty。

data class PayoutMethodCard(
    @JsonProperty("payment_account_id")
    @JsonAlias("payout_account_id")
    val payoutAccountId: Long
)

在这种情况下,paymentAccountId可以通过payment_account_id或payout_account_id从JSON序列化,但当反序列化回JSON时,将使用JSONProperty,并使用payment_account_id。

刚刚测试,这是有效的:

public class Coordinates {
    byte red;

    @JsonProperty("r")
    public byte getR() {
      return red;
    }

    @JsonProperty("red")
    public void setRed(byte red) {
      this.red = red;
    }
}

其思想是方法名应该是不同的,因此jackson将其解析为不同的字段,而不是一个字段。

下面是测试代码:

Coordinates c = new Coordinates();
c.setRed((byte) 5);

ObjectMapper mapper = new ObjectMapper();
System.out.println("Serialization: " + mapper.writeValueAsString(c));

Coordinates r = mapper.readValue("{\"red\":25}",Coordinates.class);
System.out.println("Deserialization: " + r.getR());

结果:

Serialization: {"r":5}
Deserialization: 25