简体   繁体   English

如何在Java Response对象中返回JsonArray

[英]How to return JsonArray in a Java Response object

I'm trying to implement java based web-service server which returns to Json and java script based web-service client. 我正在尝试实现基于Java的Web服务服务器,该服务器返回到基于Json和java脚本的Web服务客户端。 Here is my java part : 这是我的java部分:

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

Now, when I call this function from my js client, I got : 现在,当我从我的js客户端调用此函数时,我得到:

POST http://localhost:8080/myapp/recs 500 (Request failed.)

But when I replace the for loop and return with the following code snipped I got response in my js correctly. 但是当我替换for循环并返回以下代码时,我在js中得到了正确的响应。

Changed part : 改变部分:

// 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. 自从我第一次使用Web服务以来,我在调试代码时遇到了一些困难。

EDIT 编辑

By the way, I get also another error when I try to first version of getRecommendations() functions(with loop) 顺便说一句,当我尝试第一个版本的getRecommendations()函数(带循环)时,我还得到另一个错误

     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.

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. 但正如我所说,当我删除循环并将第二个代码剪切到getRecommendations()函数时,两个错误都消失了,我在我的网站上得到了响应。

EDIT2 EDIT2

When I changed the loop and return statement of getRecommendations() function with the below I again get the same errors 当我改变循环并返回getRecommendations()函数的语句时,我再次得到相同的错误

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

EDIT 3 编辑3

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. 据我所知, createObjectBuilder().build()JsonArrayBuilder.build()返回一个JSON object ,我的getRecommendations()函数中的这个构建语句的下面甚至没有运行。 So, I think my problem how could I give Access-Control-Allow-Origin permission to this object? 所以,我认为我的问题是如何为这个对象提供Access-Control-Allow-Origin权限?

If it is ok to use a third Party Library, using Google's Gson could be an efficient solution in this case. 如果可以使用第三方库,在这种情况下使用Google的Gson可能是一种有效的解决方案。 When converting Models to JSON it is quite handy. 将模型转换为JSON时非常方便。 What you can do is something like this. 你能做的就是这样。

ArrayList<Recommendation> recommendationList = new ArrayList<Recommendation>();
Gson gson = new Gson(); String jsonData = gson.toJson(reccomendationList);

To use it as a dependency in your POM file you could do this. 要将它用作POM文件中的依赖项,您可以执行此操作。

<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.3.1</version>
  <scope>compile</scope>
</dependency>

You should try simplest approach: 你应该尝试最简单的方法:

return Response.ok().entity(recommendation).header("Access-Control-Allow-Origin", "*")
                    .header("Access-Control-Allow-Methods", "POST").allow("OPTIONS").build();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM