Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jax-rs(Jersey) to Consumes Array of Json object in POST request

Using the jax-rs(Jersey) I am try to implement a POST request that take a list of JSON object

//The resource look like this
@Path("/path")
@POST
@Consumes(MediaType.APPLICATION_JSON)
public void setJsonl(List<SomeObj> test) {
  //do work
  System.out.println(test);
}


//The class to define the json structure
@XmlRootElement
public class SomeObj{

private String tag;
private String value;

public String getTag() {
 return tag;
}

public void setTag(String tag) {
  this.tag = tag;
}

public String getValue() {
  return value;
}

public void setValue(String value) {
  this.value = value;
}
}

how ever when I try to test the REST api using curl I always get a "bad request" error, am I missing something here?

curl -X POST -H "Content-Type: application/json" -d '{"SomeObj":[{"tag":"abc", "value":"ghi"},{"tag":"123", "value":"456"}]}' http://{host_name}:8080/path_to_resource
like image 247
LOK Avatar asked Jun 28 '12 01:06

LOK


People also ask

How do I return a JSON object to a jersey?

Jersey endpoints and return a JSON responseGET /json/ , returns a JSON string. GET /json/{name} , returns an User object containg the {name} in JSON string. GET /json/all , returns a list of User objects in JSON string. POST /json/create , accepts JSON data and returns a status 201 .

Does Jaxrs use Jackson?

Open Liberty's JAX-RS 2.0 implementation uses Jackson as its default JSON provider.

Does Jersey use Jackson?

Jersey uses Jackson internally to convert Java objects to JSON and vice versa.

What is Jax-RS and Jersey?

The JAX-RS (JSR 311: The Java API for RESTful Web Services) specification provides a standardized Java-based approach to implementing REST-style web services. Jersey is the reference implementation of JAX-RS and I provide a brief introduction to JAX-RS via Jersey in this blog post.


2 Answers

If you don't mind changing the signature of your method:

import org.json.JSONArray;

    //The resource look like this
    @Path("/path")
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    public void setJsonl(String array){
        JSONArray o = new JSONArray(last_data);
        System.out.println(o.toString());
like image 65
user311174 Avatar answered Sep 20 '22 12:09

user311174


a late answer but may be helpful for others Post this:

[{"tag":"abc", "value":"ghi"},{"tag":"123", "value":"456"}]

Because by sending this:

{"SomeObj":[{"tag":"abc", "value":"ghi"},{"tag":"123", "value":"456"}]}

you are posting an object with a single 'SomeObj' named property. you are not posting an array

like image 39
Harun Daloğlu Avatar answered Sep 19 '22 12:09

Harun Daloğlu