简体   繁体   中英

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

Now, when I call this function from my js client, I got :

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.

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.

EDIT

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.

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

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

EDIT 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. So, I think my problem how could I give Access-Control-Allow-Origin permission to this object?

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

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>

You should try simplest approach:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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