skip to Main Content

How do I use different names for serialization and deserialisation when using records?

java

public record testRecrd(@JsonProperty("foo bar") String fooBar){}

json

{
  foo bar : "test"
}

Can I modify this record or is there any modifier I can use so when I deserialise the record I get

{
 fooBar : "test"
} 

2

Answers


  1. Chosen as BEST ANSWER

    Fixed using @JsonAlias as suggested in the accepted answer

    public record testRecrd(@JsonAlias("foo bar") String fooBar){}
    

    Json returns:

    {
     fooBar : "test"
    }
    

  2. You need to use @JsonAlias for deserialization:

    Annotation that can be used to define one or more alternative names for a property, accepted during deserialization as alternative to the official name.

    public record TestRecord(@JsonProperty("foo bar") @JsonAlias("fooBar") String fooBar) {
    }
    

    Jackson will first search for foo bar and only if it’s missing for fooBar.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search