How do I expose data in a JSON format through a web service using Java?

后端 未结 9 1866
攒了一身酷
攒了一身酷 2021-01-30 14:23

Is there an easy way to return data to web service clients in JSON using java? I\'m fine with servlets, spring, etc.

9条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-30 15:16

    I have found google-gson compelling. It converts to JSON and back. http://code.google.com/p/google-gson/ It's very flexible and can handle complexities with objects in a straightforward manner. I love its support for generics.

    /*
    * we're looking for results in the form
    * {"id":123,"name":thename},{"id":456,"name":theOtherName},...
    *
    * TypeToken is Gson--allows us to tell Gson the data we're dealing with
    * for easier serialization.
    */
    Type mapType = new TypeToken>>(){}.getType();
    
    List> resultList = new LinkedList>();
    
    for (Map.Entry pair : sortedMap.entrySet()) {
        Map idNameMap = new HashMap();
        idNameMap.put("id", pair.getKey());
        idNameMap.put("name", pair.getValue());
        resultList.add(idNameMap);
    }
    
    return (new Gson()).toJson(resultList, mapType);
    

提交回复
热议问题