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();
    });
}
1

3 Answers 3

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();
}  
Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

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?
You're not returning a string, but the response will always be one before parsed. Read more about that here stackoverflow.com/questions/1973140/… in the first answer.
0
@GET
@Produces ("application/json")

if you annotate with this it should work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.