简体   繁体   中英

Sending JSON array of strings using Jersey

I am trying to send JSON array of string and perform some task on serverside. Here is my JS:

var x = ["Salam","Saghol","11"]

$.ajax({
url: '../rest/group/addusers',
type: 'POST',
data: JSON.stringify(x),
contentType: 'application/json',
dataType: 'json',
async: false,
success: function(msg) {
    alert(msg);
}
});

And my Java method:

@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("/addusers")
public Response addUsersToGroup(List<String> users) {
    System.out.println(users);
    return Response.status(Response.Status.OK).entity("Salam").build();
}

When I send the request I get "415 (Unsupported Media Type)" error message.

Please help me just passing the array elements (Strings) to the method below.

Thanks in advance.

PS Here are my headers: 在此处输入图片说明

The problem here is that the "users" parameter can't be deserialized. While my idea might be clear, the logic is not correct enough programmatically.

Usually data from POST are extracted using query parameters (using "=","?","&" as separator). In my case I put the data directly to POST output stream. And getting all data in string representation is more logical.

So I changed the code into this:

@POST
@Produces(MediaType.TEXT_HTML)
@Consumes(MediaType.APPLICATION_JSON)
@Path("/addusers")    
public Response addUsersToGroup(String users) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    List<String> l = mapper.readValue(users, List.class);

    for (String s : l) {
        System.out.println("Item: "+s);
    }


    return Response.status(Response.Status.OK).entity("Salam").build();
}

And problem is solved. Thanks for attention.

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