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

后端 未结 9 1862
攒了一身酷
攒了一身酷 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<List<Map<String, String>>>(){}.getType();
    
    List<Map<String, String>> resultList = new LinkedList<Map<String, String>>();
    
    for (Map.Entry<String, String> pair : sortedMap.entrySet()) {
        Map<String, String> idNameMap = new HashMap<String, String>();
        idNameMap.put("id", pair.getKey());
        idNameMap.put("name", pair.getValue());
        resultList.add(idNameMap);
    }
    
    return (new Gson()).toJson(resultList, mapType);
    
    0 讨论(0)
  • 2021-01-30 15:21

    Yup! Check out json-lib

    Here is a simplified code snippet from my own code that send a set of my domain objects:

    private String getJsonDocumenent(Object myObj) (
        String result = "oops";
        try {
            JSONArray jsonArray = JSONArray.fromObject(myObj);
    
            result = jsonArray.toString(2);  //indent = 2
    
        } catch (net.sf.json.JSONException je) {
    
            throw je;
        }
        return result;
    }
    
    0 讨论(0)
  • 2021-01-30 15:27

    http://www.json.org/java/index.html has what you need.

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