如何在Java Response对象中返回JsonArray [英] How to return JsonArray in a Java Response object
问题描述
我正在尝试实现基于Java的Web服务服务器,该服务器返回Json和基于Java脚本的Web服务客户端.这是我的Java部分:
I'm trying to implement java based web-service server which returns to Json and java script based web-service client. Here is my java part :
@Path("/myapp")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class MyRecommender {
@POST
@Path("/recs")
public Response getRecommendations() {
//Assume recommendation List contains some Recommendation objects
//I removed it for simplicity.
List<Recommendation> recommendation;
JsonArrayBuilder builder = Json.createArrayBuilder();
for (Recommendation rec : recommendations) {
builder.add(Json.createObjectBuilder().add("firstPersonName", "\"" + rec.getFirstPerson().getName() + "\"")
.add("firsPersonURL", "\"" + rec.getFirstPerson().getURL() + "\"")
.add("secondPersonName", "\"" + rec.getSecondPerson().getName() + "\"")
.add("secondPersonURL", "\"" + rec.getSecondPerson().getURL() + "\"")
.add("score", "\"" + rec.getSimilarity() + "\""));
}
JsonArray jsonData = builder.build();
return Response.ok(jsonData, MediaType.APPLICATION_JSON).header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "POST").allow("OPTIONS").build();
}
}
}
现在,当我从js客户端调用此函数时,我得到了:
Now, when I call this function from my js client, I got :
POST http://localhost:8080/myapp/recs 500 (Request failed.)
但是当我替换for循环并返回以下代码时,我在js中得到了正确的响应.
But when I replace the for loop and return with the following code snipped I got response in my js correctly.
更改的部分:
// remove for loop and change jsonData type.
String jsonData = "{\"name\":\"John\"}";
return Response.ok(jsonData, MediaType.APPLICATION_JSON).header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "POST").allow("OPTIONS").build();
所以,我想知道可能是什么问题?自从我第一次使用网络服务以来,调试代码就有些困难.
So, I wonder what might be problem ? Since its my first time with web-services, I have some difficulty to debug my code.
编辑
顺便说一句,当我尝试使用getRecommendations()函数的第一个版本(带有循环)时,我还会遇到另一个错误
By the way, I get also another error when I try to first version of getRecommendations() functions(with loop)
XMLHttpRequest cannot load http://localhost:8080/myapp/recs.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:3000' is therefore not allowed access.
The response had HTTP status code 500.
但是正如我所说,当我删除循环并将第二段代码插入到getRecommendations()函数中时,两个错误都消失了,并且我在网站上得到了响应.
But as I said, When I remove the loop and put second code snipped into getRecommendations() functions, both of the errors are gone and I get the response in my website.
EDIT2
当我用下面的内容更改getRecommendations()函数的循环和返回语句时,我再次 get 相同的错误
When I changed the loop and return statement of getRecommendations() function with the below I again get the same errors
JsonObject value = Json.createObjectBuilder()
.add("name", "John").build();
return Response.ok(value, MediaType.APPLICATION_JSON).header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "POST").allow("OPTIONS").build();
编辑3
据我了解,createObjectBuilder().build()
或JsonArrayBuilder.build()
在我的getRecommendations()函数中甚至未运行此build语句的下面返回JSON object
.因此,我认为我的问题是如何授予该对象的Access-Control-Allow-Origin权限?
As far as I understood, createObjectBuilder().build()
or JsonArrayBuilder.build()
return an JSON object
and below of this build statement in my getRecommendations() function is not even run. So, I think my problem how could I give Access-Control-Allow-Origin permission to this object?
推荐答案
如果可以使用第三方库,在这种情况下,使用Google的Gson可能是一种有效的解决方案.将模型转换为JSON时非常方便. 您可以做的就是这样.
If it is ok to use a third Party Library, using Google's Gson could be an efficient solution in this case. When converting Models to JSON it is quite handy. What you can do is something like this.
ArrayList<Recommendation> recommendationList = new ArrayList<Recommendation>();
Gson gson = new Gson();
String jsonData = gson.toJson(reccomendationList);
ArrayList<Recommendation> recommendationList = new ArrayList<Recommendation>();
Gson gson = new Gson();
String jsonData = gson.toJson(reccomendationList);
要将其用作POM文件中的依赖项,您可以这样做.
To use it as a dependency in your POM file you could do this.
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3.1</version>
<scope>compile</scope>
</dependency>
这篇关于如何在Java Response对象中返回JsonArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!