简体   繁体   中英

Passing JSONObject in RestFul Webservice

I am using RestFul Webservice with JBoss Server to deploy the app to receive the JSONObject to my web service ,to test that i have created the web service and written test cases for it .Now i got hung up in passing the JSONobject from test case to web services , when i pass the json object to @post service calls it responses that Null Pointer Exception , even i have tried with passing string to it it responds null values. I have used Annotations as follows in webservice

@consumes({Mediatype.APPLICATION_JSON})

@Consumes("application/json")

Test case As:

    @Test
   public void testgetmsg() {
    String msg = "{\"patient\":[{\"id\":\"6\",\"title\":\"Test\"}]}";
    try {
        JSONObject obj = new JSONObject(new JSONTokener(msg));
            WebResource resource = client.resource( "https://localhost:8443/../../resources/create");
        ClientResponse response = resource.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).
                        entity(obj).post(ClientResponse.class,JSONObject.class);
                 }
    }

can any body guide me to proceed further ?

Thanks in Advance

You don't need to create the json object, you can just pass the string.

you should

 ClientResponse response = resource.type(MediaType.APPLICATION_JSON)
                                   .accept(MediaType.APPLICATION_JSON)
                                   .post(ClientResponse.class, msg);
//CLIENT

public static void createStudent() {
    String input = "{\"id\":12,\"firstName\":\"Fade To Black\",\"lastName\":\"Joy\"}";
    ClientResponse response = service.path("class/post")
            .type("application/json").post(ClientResponse.class, input);
    System.out.println("Output from Server .... \n");
    String output = response.getEntity(String.class);
    System.out.println(output);
    System.out.println(response.getStatus()+ "OK");
}

Instead of using code client you can use add on firefox (POSTER) to passing value as json or formparam...

  // create new student SERVER
   //class

   @POST
   @Path("post")
   @Consumes(MediaType.APPLICATION_JSON)
   @Produces(MediaType.APPLICATION_JSON)
   public Response createStudent(Student st) {
       // add new student 
       StudentDAO.instance.getModelStudent().put("8", st);
       // response status code
       return Response.status(200).entity(st).build();
    }

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