Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在响应中发回JSON对象(不是字符串版本)_Javascript_Java_Json_Web Services_Rest - Fatal编程技术网

Javascript 在响应中发回JSON对象(不是字符串版本)

Javascript 在响应中发回JSON对象(不是字符串版本),javascript,java,json,web-services,rest,Javascript,Java,Json,Web Services,Rest,我正在用Java开发一个restful web服务,我有一个返回有效JSON的方法: @GET @Produces(MediaType.APPLICATION_JSON) public Response getJSON() { String json = "{\"data\": \"This is my data\"}"; return Response.ok(json).build(); } 我遇到的问题是JSON是字符串形式的。 如何以对象形式将其发送回?在其当

我正在用Java开发一个restful web服务,我有一个返回有效JSON的方法:

@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getJSON()
{   
    String json = "{\"data\": \"This is my data\"}";
    return Response.ok(json).build();
}   
我遇到的问题是JSON是字符串形式的。 如何以对象形式将其发送回?在其当前状态下,我无法在响应返回时立即使用它,因为响应数据将以字符串形式返回

以防万一,这里是我从javascript端调用的web服务

//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();
    });
}
尝试在ResponseBuilder第二个参数中传递MediaType:

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

如果您使用此注释,它应该会起作用

您所要做的就是在JavaScript中使用JSON.parse

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

无论从后端发送什么,responseGet函数都不会返回已解析的对象

可能与重复,所以您是说返回JSON字符串是从后端返回日期的正常/正确方法?不管怎样,我总是需要使用JSON.parse,不管怎样?您没有返回字符串,但在解析之前,响应总是一个字符串。在第一个答案中阅读更多关于这方面的内容。
promise.then(
function(response) { 
    response = JSON.parse(response);
    console.log("Success!", response);
}