1

I'm working on a restful web service in Java and I have this method that returns valid JSON:

@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getJSON()
{   
    String json = "{\"data\": \"This is my data\"}";
    return Response.ok(json).build();
}   

The issue I am having is that the JSON is in its string form. How would I send it back in the Object form? In its current state I cannot work with it as soon as my response returns, because the response data is coming back as a string

Just in case here is my web service call from the javascript side

//Use of the promise to get the response
let promise = this.responseGet()
promise.then(
    function(response) { //<--- the param response is a string and not an object :(
        console.log("Success!", response);
    }, function(error) {
        console.error("Failed!", error);
    }
);

//Response method    
responseGet() 
{
    return new Promise(function(resolve, reject) {

        let req = new XMLHttpRequest();
        req.open('GET', 'http://localhost:8080/TestWebService/services/test');

        req.onload = function() {
          if (req.status == 200) {
            resolve(req.response);
          }
          else {
            reject(Error(req.statusText));
          }
        };

        req.onerror = function() {
          reject(Error("There was some error....."));
        };

        req.send();
    });
}
Tyler
  • 113
  • 1
  • 5
  • Probably duplicated with [HTTPResponse as JSON in Java](http://stackoverflow.com/questions/17191412/httpresponse-as-json-in-java) – Top.Deck Mar 01 '17 at 19:55

3 Answers3

1

Try passing a MediaType in the ResponseBuilder second parameter:

@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getJSON()
{   
  String json = "{\"data\": \"This is my data\"}";
  return Response.ok(json, MediaType.APPLICATION_JSON).build();
}  
Corey
  • 5,818
  • 2
  • 24
  • 37
0
@GET
@Produces ("application/json")

if you annotate with this it should work.

0

All you have to do is using JSON.parse() in your JavaScript.

promise.then(
function(response) { 
    response = JSON.parse(response);
    console.log("Success!", response);
}

Your responseGet function won't return a parsed object, no matter what you send from the backend.

baao
  • 71,625
  • 17
  • 143
  • 203
  • So you're saying that returning a JSON String is the normal/proper way to return date from the backend? And no matter what I always would need to use JSON.parse() regardless? – Tyler Mar 01 '17 at 23:41
  • You're not returning a string, but the response will always be one before parsed. Read more about that here http://stackoverflow.com/questions/1973140/parsing-json-from-xmlhttprequest-responsejson in the first answer. – baao Mar 01 '17 at 23:47