First of all, download the json library for java from this location.
Now, to return the JSON data, you need to follow its own format, for example:
{ "firstName": "John", "lastName": "Smith", "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": 10021 }, "phoneNumbers": [ "212 732-1234", "646 123-4567" ] }
As you can see above, json data can have a key pair: value, an object can be stored inside { } , an array can be stored in [ ] , etc.
Now, to convert your response to a JSON object, you need to import the following statement into a jsp file:
import net.sf.json.JSONObject;
(it may vary depending on what you download, you can study javadoc for more details)
Now, consider the following code to create a json object and return it:
JSONObject object=new JSONObject(); object.put("name","Amit Kumar"); object.put("employeeList",employeeList); .... .... System.out.println("json object = "+object); return object;
It automatically converts the key: value pair to the correct JSON object ...
UPDATE:
Required Libraries:
commons-lang 2.3 commons-beanutils 1.7.0 commons-collections 3.2 commons-logging 1.1 ezmorph 1.0.4.jar json-lib-2.2.2-jdk15.jar
You can download all from here :
To convert arraylist to json, use the following code example:
List mybeanList = new ArrayList(); mybeanList.add(myBean1); mybeanList.add(myBean2); JSONArray jsonArray = JSONArray.fromObject(mybeanList); System.out.println("==== : "+jsonArray); Map map = new HashMap(); map.put("beanlist", jsonArray); JSONObject jsonObject = JSONObject.fromObject(map); return jsonObject;