REST with Java (JAX-RS) using Jersey

前端 未结 2 1619
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-11 12:51

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

Then I used the Hibernate Technology to map the dat

相关标签:
2条回答
  • 2020-12-11 13:00
    1. Response.ok().enity(object).build() is the correct way to return data
    2. You really want to move your hibernate stuff to a data access tier... it's going to be hard to manage intermingled with your service tier
    3. I completely disagree with smcg about using a helper method to map the java to json. Use the jax-rs annotations on your beans to do it unless you have really complicated requirements: see http://wiki.fasterxml.com/JacksonAnnotations
    0 讨论(0)
  • 2020-12-11 13:17

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

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

    In the case of returning a list of things, use a JSONArray instead of a JSONObject.

    You'll want a helper method to map the 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 doesn't force you to have public getters and setters for all your fields.

    0 讨论(0)
提交回复
热议问题