简体   繁体   中英

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.

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\\":\\"asdasd@gmail.com\\",\\"name\\":\\"asdasd\\"},{\\"email\\":\\"Dan@gmail.com\\",\\"name\\":\\"Dan\\"},{\\"email\\":\\"Ion@gmail.com\\",\\"name\\":\\"dsadsa\\"},{\\"email\\":\\"Dan@gmail.com\\",\\"name\\":\\"ertert\\"},{\\"email\\":\\"Ion@gmail.com\\",\\"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

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

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