Search code examples
javajsonjackson

Different names of JSON property during serialization and deserialization


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

For example, I have class "Coordiantes".

class Coordinates{
  int red;
}

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
}

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;
    }
}

but I got an exception:

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


Solution

  • 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;
        }
    }
    

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

    Here is test code:

    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());
    

    Result:

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