REST with Java (JAX-RS) using Jersey

I developed a quiet web service through Jersey in Java (JAX-RS): http://www.vogella.com/articles/REST/article.html

Then I used Hibernate technology to map data to a database.

Finally, I developed an Android application to display data.

This is an example of a method in my web service:

@GET @Path("/project_id/username/get/{projectId}/{username}/") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response deliverableList(@PathParam("projectId") long projectId, @PathParam("username") String username) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); List<Deliverable> list = null; try { list= (List<Deliverable>) session.createQuery( "from Deliverable as d where d.project.id= :id").setLong("id", projectId).list(); } catch (HibernateException e) { e.printStackTrace(); session.getTransaction().rollback(); } session.getTransaction().commit(); return Response.status(201).entity(list).build(); } 

as you can see, I used "Response.status (201) .entity (list) .build ()" to pass the list of data. Is this a good way? if not what you propose to transmit data. Please support your explanation with some codes and examples.

+1
source share
2 answers
  • Response.ok (). enity (object) .build () is the correct way to return data.
  • Are you sure you want to transfer your sleep mode to the data access layer ... it will be difficult for you to control the mix with your service level
  • I totally disagree with smcg about using a helper method to map java to json. Use jax-rs annotations on your beans to do this if you don't have really complex requirements: see http://wiki.fasterxml.com/JacksonAnnotations
+2
source

It seems to me that you are relying on something to automatically map your Java objects to JSON - possibly Jackson. I personally do not prefer this method. Instead, I use Jettison and create my own mapping from Java to the Jettison JSONObject. Then I use JSONObject (or JSONArray) as an object. My return statement would be something like this:

 return Response.ok().entity(myObjectAsJSON).build(); 

If returning a list of things, use a JSONArray instead of a JSONObject.

You will need a helper method to map a Java object to JSON.

 public JSONArray deliverableListToJSON(List<Deliverable> deliverables) throws JSONException { JSONArray result = new JSONArray(); for(Deliverable deliverable : deliverables) { JSONObject deliverableJSON = new JSONObject(); deliverableJSON.put("importantValue", deliverable.getImportantValue()); result.put(deliverableJSON); } return result; } 

This approach gives you more flexibility and does not force you to have public recipients and setters for all of your fields.

0
source

Source: https://habr.com/ru/post/922854/


All Articles