序列化和反序列化期间JSON属性的不同名称 [英] Different names of JSON property during serialization and deserialization

查看:325
本文介绍了序列化和反序列化期间JSON属性的不同名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible: to have one field in class, but different names for it during serialization/deserialization in Jackson library?

例如,我有类Coordiantes 。

For example, I have class "Coordiantes".

class Coordinates{
  int red;
}

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

For deserialization from JSON want to have format like this:

{
  "red":12
}

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

But when I will serialize object, result should be like this one:

{
  "r":12
}

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

I tried to implement this by applying @JsonProperty annotation both on getter and setter (with different values):

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.exc.UnrecognizedPropertyException:无法识别的字段red

org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "red"


推荐答案

刚刚测试过,这个有效:

Just tested and this works:

public class Coordinates {
    byte red;

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

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

这个想法是方法名称应该不同,所以jackson将其解析为不同的字段,而不是一个字段。

The idea is that method names should be different, so jackson parses it as different fields, not as one field.

这是测试代码:

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

这篇关于序列化和反序列化期间JSON属性的不同名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆