skip to Main Content

For serialising a java object’s name field in json, if I have a java class:

Class Test {
  private String name;

}

When I create the Test object with a name.

In scenario one, when I serialise the test object, I would like the name field to be represented as name.

{ "name": "Bob"}

In scenario two , when I serialise the test object, I would like the name field to be represented as firstName.

{ "firstName": "Bob"}

How can I achieve this with jackson.

Thanks

2

Answers


  1. You have to use @JsonProperty annotation to set the desired custom field name that you want to show on serialization.

    public class Test {
      
       private String name; 
    
       public void setName(String name) {
         this.name = name;
       }
    
       @JsonProperty("firstName")
       public String getName() {
          return this.name;
       }
    
    }
    
    Login or Signup to reply.
  2. You can user Views.

    Views

    public class Views {
    
        public static class Foo {
        }
    
        public static class Bar {
        }
    }
    

    DTO

    import com.fasterxml.jackson.annotation.JsonProperty;
    import com.fasterxml.jackson.annotation.JsonView;
    
    public class User {
        @JsonView(Views.Foo.class)
        @JsonProperty("name")
        public String name;
    
        @JsonView(Views.Bar.class)
        @JsonProperty("firstName")
        public String firstName;
    
        @JsonProperty("lastName")
        public String lastName;
    
        public String getFirstName() {
            return firstName;
        }
    
        public void setFirstName(String firstName) {
            this.name = this.firstName = firstName;
        }
    
        public String getLastName() {
            return lastName;
        }
    
        public void setLastName(String lastName) {
            this.lastName = lastName;
        }
    }
    

    Test

    class JacksonViewTest {
    
        @Test
        void viewFoo() throws IOException {
            User user = new User();
            user.setFirstName("John");
            user.setLastName("Doe");
    
            String json = new ObjectMapper()
                    .writerWithView(Views.Foo.class)
                    .writeValueAsString(user);
    
            assertSame("{"name":"John","lastName":"Doe"}", json);
        }
    
        @Test
        void viewBar() throws IOException {
            User user = new User();
            user.setFirstName("John");
            user.setLastName("Doe");
    
            String json = new ObjectMapper()
                    .writerWithView(Views.Bar.class)
                    .writeValueAsString(user);
    
            assertSame("{"firstName":"John","lastName":"Doe"}", json);
        }
    
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search