4

I am working with a simple Spring Boot based RestController. I am returning JSON, but I am unable to control the name of the keys generated in the response. The POJO looks like this:

public class SomePojo {
   @JsonProperty("name")
   private String fullName;
   @JsonProperty("name")
   public String getFullName() {
     return fullName;
   }
   public void setFullName(String fullName) {
     this.fullName = fullName;
   }
}

If I create a new instance as follows:

SomePojo sm = new SomePojo();
sm.setFullName("John Doe");

and return the instance in the @ResponseBody. I expect to see

{ "name" : "John Doe" }

but I am seeing

{ "fullName" : "John Doe" }

I tried using the @JsonProperty("name") annotation on both the property as well as its getter, but it is not working. Spring Boot version is 1.4.2. Any suggestions as to what I am missing?

Web User
  • 7,438
  • 14
  • 64
  • 92
  • may be this [link](http://stackoverflow.com/questions/8560348/different-names-of-json-property-during-serialization-and-deserialization/8560615#8560615) will help you. – Hardik Bharadava Dec 05 '16 at 07:32
  • http://stackoverflow.com/questions/28324352/how-to-customise-the-jackson-json-mapper-implicitly-used-by-spring-boot might help. – YYY Dec 05 '16 at 07:33
  • 1
    set the @JsonProperty in getter and setter it will work. – VelNaga Dec 05 '16 at 10:04
  • @VelNaga yes, that worked! Please add this as an answer so I can select it as the right answer. – Web User Dec 05 '16 at 15:50
  • @WebUser I posted the answer. Thank you for your response. – VelNaga Dec 05 '16 at 15:52

2 Answers2

7

Set the @JsonProperty in getter and setter it will work

VelNaga
  • 3,593
  • 6
  • 48
  • 82
0

What if you change this.fullName to this.name

public void setFullName(String fullName) { this.fullName = fullName; }

nish
  • 1,008
  • 4
  • 17
  • 34