是否可能:在类中有一个字段,但在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”


当前回答

你可以写一个序列化类来实现:

public class Symbol

{
     private String symbol;

     private String name;

     public String getSymbol() {
        return symbol;
    }
    public void setSymbol(String symbol) {
        this.symbol = symbol;
    }    
    public String getName() {
        return name;
    }    
    public void setName(String name) {
        this.name = name;
    }
}
public class SymbolJsonSerializer extends JsonSerializer<Symbol> {

    @Override
    public void serialize(Symbol symbol, JsonGenerator jgen, SerializerProvider serializers) throws IOException, JsonProcessingException {
        jgen.writeStartObject();

        jgen.writeStringField("symbol", symbol.getSymbol());
         //Changed name to full_name as the field name of Json string
        jgen.writeStringField("full_name", symbol.getName());
        jgen.writeEndObject(); 
    }
}

            ObjectMapper mapper = new ObjectMapper();

            SimpleModule module = new SimpleModule();
            module.addSerializer(Symbol.class, new SymbolJsonSerializer());
            mapper.registerModule(module); 

            //only convert non-null field, option...
            mapper.setSerializationInclusion(Include.NON_NULL); 

            String jsonString = mapper.writeValueAsString(symbolList);

其他回答

我将两个不同的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;
    }
}

你可以使用在jackson 2.9.0中引入的@jsonAlias

例子:

public class Info {
  @JsonAlias({ "red" })
  public String r;
}

在序列化期间使用r,但在反序列化期间允许使用red作为别名。不过,这仍然允许反序列化r。

在属性上同时使用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。

你可以使用这个变体:

import lombok.Getter;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonProperty;

//...

@JsonProperty(value = "rr") // for deserialization
@Getter(onMethod_ = {@JsonGetter(value = "r")}) // for serialization
private String rrrr;

使用Lombok吸气器

可以有普通的getter/setter对。您只需要在@JsonProperty中指定访问模式

下面是单元测试:

public class JsonPropertyTest {

  private static class TestJackson {

    private String color;

    @JsonProperty(value = "device_color", access = JsonProperty.Access.READ_ONLY)
    public String getColor() {
      return color;
    };

    @JsonProperty(value = "color", access = JsonProperty.Access.WRITE_ONLY)
    public void setColor(String color) {
      this.color = color;
    }

  }

  @Test
  public void shouldParseWithAccessModeSpecified() throws Exception {
    String colorJson = "{\"color\":\"red\"}";
    ObjectMapper mapper = new ObjectMapper();
    TestJackson colotObject = mapper.readValue(colorJson, TestJackson.class);

    String ser = mapper.writeValueAsString(colotObject);
    System.out.println("Serialized colotObject: " + ser);
  }
}

我得到的输出如下:

Serialized colotObject: {"device_color":"red"}