-1

I am currently working with with web services for the first time and I have to write some examples of different web services in Jersey using Maven,

But I can only seem to get it to work in Spark (Here's My spark example)

//Hashmap Example
get("add/:num1/:num2", new Route() {

    @Override
    public Object handle(Request rqst, Response rspns) throws Exception {
        rspns.type("application/json");

        int num1 = Integer.parseInt(rqst.params(":num1"));
        int num2 = Integer.parseInt(rqst.params(":num2"));
        HashMap<String, Integer> map = new HashMap<>();
        map.put("result", num1+num2);
        Gson gson = new Gson();
        return gson.toJson(map);
    }
});

I just need some help writing it for a Jersey example ?

Any help you can offer would be great

2 Answers2

0

First, with Jersey you need to register a JSonProvider, so that you can return an Object and it will be serialized for you in JSON. You can alternatively support XML with no more effort.

Personally I use Jackson. The default with Jersey is Moxy, which doesn't support Maps, and has "issues" even with simple List (you need to wrap them) see this post

Configuring Jersey with Jackson : https://jersey.java.net/documentation/latest/media.html#json.jackson

Moxy issue with Map : How to return a JSON object from a HashMap with Moxy and Jersey

Here's a working example of a Jersey web service, returning a Map, given you are using Jackson

@GET
@Path("add/{num1}/{num2}")
@Produces(MediaType.APPLICATION_JSON)
public Response getClubNames(@PathParam("num1") Integer num1, @PathParam("num2") Integer num2) {

    Map<String, Object> returnMap = new HashMap<String, Object>();

    returnMap.put("resultAsString", Integer.toString(num1 + num2));
    returnMap.put("resultAsInt", num1 + num2);

    return Response.status(Response.Status.OK).entity(returnMap).build();

}

Personal note, as you are starting to use Jersey :

I really like Jersey. But there is a serious hard-coupling issue with HK2. https://java.net/jira/browse/JERSEY-1933. This is out of scope, but you should understand what this means before choosing a JAX-RS 2.0 implementation. In a stand alone Web Application, Jersey works like a charm.

Community
  • 1
  • 1
Filip
  • 906
  • 3
  • 11
  • 33
  • Thanks for the information but this was not quiet what I was looking for, I have now figured it out and posted the answer below for anyone that needs it –  Nov 06 '15 at 09:19
0

Figured it out myself

//HashMap Example
@GET
@Path("add/{num1}/{num2}")
public String Hashmap(@PathParam("num1") int num1, @PathParam("num2") int num2){
          HashMap<String, Integer> map = new HashMap<>();
          map.put("result", num1+num2);
          Gson gson = new Gson();
          return gson.toJson(map);
}
  • Note that it is not because you "can" create the Json yourself that you "should". Other than that, I don't see how your solution differs from mine. – Filip Nov 06 '15 at 12:43