users@jersey.java.net

application/json programming model

From: Arun Gupta <Arun.Gupta_at_Sun.COM>
Date: Thu, 30 Aug 2007 11:33:36 -0700

In order to return a JSON array like:

[{"name":"California","value":"California"},{"name":"New
York","value":"New York"},{"name":"Alabama"
,"value":"Alabama"},{"name":"Texas","value":"Texas"}]

I have to write the following code:

-- cut here --
     @HttpMethod("GET")
     @ProduceMime("application/json")
     public JSONArray getMessage() throws JSONException {
         String[] states = { "California", "New York", "Alabama", "Texas"};
         JSONArray array = new JSONArray();
         for (String s : states) {
             JSONObject item = new JSONObject();
             item.put("name", s).put("value", s);
             array.put(item);
         }

         return array;
     }
-- cut here --

I think this is too involving and low-level. Can the code be something
like the following ?

-- cut here --
@JSONObject
ItemBean {
   ItemBean(String name, String value) { ... }

   @JSONObjectKey
   public String getName() { ... }

   @JSONObjectValue("value")
   public String getNameValue() { ... }
}

     @HttpMethod("GET")
     @ProduceMime("application/json")
     public List<ItemBean> getMessage() {
         String[] states = { "California", "New York", "Alabama", "Texas"};
        List<ItemBean> list = new ArrayList<ItemBean>();
         for (String s : states) {
             ItemBean bean = new ItemBean(s, s);
             list.add(bean);
         }

         return list;
     }
-- cut here --

This will require defining new annotations JSONObject, JSONObjectKey &
JSONObjectValue. I think this is more natural to a Java developer.

-Arun
-- 
Web Technologies and Standards
Sun Microsystems, Inc.
Blog: http://blogs.sun.com/arungupta