tpow
tpow

Reputation: 7894

Converting incoming JSON to Java array using Jersey

I have a REST api GET call that takes an array of strings formatted as JSON. I'd like to use Jersey to convert that array of strings to something like a string array or List. I've reviewed http://jersey.java.net/nonav/documentation/latest/json.html, but it looks like Jersey wants me to create an object that specifies how it should be mapped, which I really don't want to do because it's just a simple array.

        @GET
        public Response get(@QueryParam("json_items") String requestedItems) throws IOException
        {
            //Would like to convert requestedItems to an array of strings or list

        }

I know there are lots of libraries for this - but I'd prefer to use Jersey and not introduce any new libraries.

Upvotes: 0

Views: 3237

Answers (2)

boogie666
boogie666

Reputation: 650

Create a wrapper object for you data (in this case the Person class) and annotate it with @XMLRootElement

Your post method should look like this

@POST
@Consumes(MediaType.APPLICATION_JSON)
public void post(List<Person> people) {
    //notice no annotation on the method param
    dao.putAll(people);
    //do what you want with this method
    //also best to return a Response obj and such
}

this is the right way to do this stuff where the data is sent in the request.
but if you want to have a QueryParam as the JSON data you can do this

say your request param looks like this: String persons = "{\"person\":[{\"email\":\"[email protected]\",\"name\":\"asdasd\"},{\"email\":\"[email protected]\",\"name\":\"Dan\"},{\"email\":\"[email protected]\",\"name\":\"dsadsa\"},{\"email\":\"[email protected]\",\"name\":\"ertert\"},{\"email\":\"[email protected]\",\"name\":\"Ion\"}]}";

you notice that its a JSONObject named "person" that contains a JSONArray of other JSONObjets of type Person with name an email :P you can itterate over them like this:

    try {
        JSONObject request = new JSONObject(persons);
        JSONArray arr = request.getJSONArray("person");
        for(int i=0;i<arr.length();i++){
            JSONObject o = arr.getJSONObject(i);
            System.out.println(o.getString("name"));
            System.out.println(o.getString("email"));
        }
    } catch (JSONException ex) {
        Logger.getLogger(JSONTest.class.getName()).log(Level.SEVERE, null, ex);
    }

sry

Upvotes: 2

Enrichman
Enrichman

Reputation: 11337

Just try to add to your Response the array, like

return Response.ok(myArray).build();

and see what happen. If it's just a very simple array it should be parsed without any problem.

EDIT:

If you want to receive it then just accept an array instead of a String. Try with a List or something like this.

Otherwise you can try to parse it using an ObjectMapper

mapper.readValue(string, List.class);

Upvotes: 1

Related Questions