0

Suppose we have some RESTful resource serving this POST:

@POST
@Produces("application/json")
@Consumes("application/json")
public String doPostJson(String string) {
    ...
}

( I was able to run the above in my server so I am assuming this is a valid implementation )

Now I am thinking the doPostJson() gets String and returns String. This string could be something totally different than JSON valid string. Am I right? So what is the meaning of "application/json" if I can use any string here?

MORE: In other hand, could I just use this?

@POST
@Produces("text/plain")
@Consumes("text/plain")
public String doPostJson(String string) {
    ... /* read passed parameter as JSON valid string and return JSON string */
}
flyer
  • 1,733
  • 2
  • 19
  • 44

2 Answers2

6

Produces and Consumes annotations are used for sharing theContent-Type and Accept headers information respectively with your webservice users. Content-type header will help the receiver/consumer of your service, to treat the response as per the information in that header. If you mark the value of content-type header as application/json, then receiver can accordingly use a json parser. Similarly, using the Consumes, you are assuring that Accept header is application/json so that you can do the json parsing/unmarshalling accordingly.

Juned Ahsan
  • 63,914
  • 9
  • 87
  • 123
  • 1
    Maybe I am not feel the difference because I am only one consumer of my API... But the 'public' consumer must know the structure of the JSON returned from server, so anyone who uses this API must know/expect a JSON. Is that true? Is this Content-Type just for additional validation if server e.g. will change something in API and use some different data format? – flyer Jul 23 '13 at 18:39
  • 1
    @flyer Yes Content-Type allows the consumer of your web service to decided how to consume it. As a web service can produce different contents for example json or xml. Now how the consumer will decide, which parser he should use to parse the response. So the consumer will look into the content-type header and will then fetch a parser accordingly to consume the response. – Juned Ahsan Jul 24 '13 at 03:57
1

"application/json" is the mime-type you are serving out, see this related question for some more details link. It helps the application communicating with your application. They might completely reject the response should it be of the wrong mimetype, for example image/jpeg instead of application/json

Community
  • 1
  • 1
Zavior
  • 6,182
  • 2
  • 25
  • 36
  • Thanks for reference. It looks like most upvoted discussion I have ever seen on SO. My question is more like "how this setting helps my application"? – flyer Jul 23 '13 at 23:11