4

I'm using REST using Spring & Java 1.7

I've below model class:

private String name;
public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

And my controller is mapped to GET /person/info API. So, the controller fetches name & shows it as JSON response.

Here is the controller:

 import org.springframework.web.bind.annotation.RequestBody;
 import org.springframework.web.bind.annotation.RequestHeader;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestMethod;

@RequestMapping(value = "persons/info", method = RequestMethod.POST, consumes="application/json", produces="application/json")
public ResponseEntity<String> getPersonInfo(@RequestBody String body) throws Exception {    
    String personInfo = null;

    MyServiceJson myServiceJson = MyServiceJsonFactory.getMyServiceObject(body);

    personInfo = myService.getPersonInfo(myServiceJson);

    HttpHeaders responseHeader = new HttpHeaders();
    return Util.getResponse(personInfo, responseHeader, HttpStatus.OK);
}

I'm getting the JSON response as shown below:

{"name":"Jack"}

The problem is here is that this name string must be personName as shown below:

{"PersonName":"Jack"}

I believe it is taking the variable name from model & sending it as it is. Can any one tell me if it is possible to have different attribute name as "PersonName" with some annotation change in REST service??

I'll appreciate if someone can shed some light here!

Thanks!

Freephone Panwal
  • 1,547
  • 4
  • 21
  • 39

1 Answers1

1

If you are using the Jackson library, I guess you can spcify in that way:

@JsonProperty("PersonName")
public String getName() {
    return name;
}
Jako
  • 944
  • 14
  • 33
  • Do I need to add this annotation above method name or variable name where I declared name variable? – Freephone Panwal Feb 15 '13 at 00:33
  • I used to add the annotation before the declaration of the variable, but I think both work. – Jako Feb 15 '13 at 00:38
  • Somehow its not working for me. I still get name only instead of personName?? Do I need to change anything else? I've other attributes as well in the response? Do I need to add this annotation to each of the tag? – Freephone Panwal Feb 15 '13 at 00:44
  • What versions of Spring/Jackson are you using ? I did not have anything particular to do, but this topic may explain your problem : http://stackoverflow.com/questions/10085088/jackson-annotations-being-ignored-in-spring – Jako Feb 15 '13 at 01:04