JSON-lib is one of the standard library used for converting JSON String to any Custom Object and also any Custom Object to JSON String.
JSON-lib is one of the standard library used for converting JSON String to any Custom Object and also any Custom Object to JSON String.
This library is compatible even for lower versions of java., starting from JDK 1.3. However most of the libraries provide this functionalities starting from JDK 1.5.
The following libraries/dependencies are required along with json-lib library..,
1 2 3 4 5 6 |
json-lib-2.3-jdk13.jar ezmorph-1.0.jar commons-lang-2.6.jar commons-collections-3.2.jar commons-beanutils-1.3.jar commons-logging-1.2.jar |
For converting a String to JSONObject, JSONSerializer class is used in JSON-lib.
1 |
(JSONObject) JSONSerializer.toJSON(jsonString); |
For converting a custom Object to String,JsonConfig and JSONSerializer classes are used.
We need to define the Object we need to convert in JsonConfig class.
1 2 3 |
JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass( DummyBean.class ); JSON jsonString = JSONSerializer.toJSON(object, jsonConfig); |
Example Below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
public class JSONObjectConversion { public JSONObjectConversion() throws Exception { System.out.println("Start"); String json = "{\"name\": \"karthick\", \"value\": \"VALUE\"}"; DummyBean dummyBean = convertJSONToObject(json); System.out.println(dummyBean); System.out.println(dummyBean.name); System.out.println(dummyBean.value); String jsonString = convertObjectToJSON(dummyBean); System.out.println("JSON String:" + jsonString); } /** This method converts the string to JSONObject instance of json-lib class. And converts the JSONObject to the JSON structured Bean. * The fields names in JSON should be same as the parameters name in the Bean. Also all the parameters should have getters and setters. * * */ public DummyBean convertJSONToObject(String json) { JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON(json); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass( DummyBean.class); DummyBean dummyBean = (DummyBean) JSONSerializer.toJava( jsonObject, jsonConfig ); return dummyBean; } /** This method converts the JSONObject instance of json-lib class. And converts the JSONObject to the JSON structured Bean. * The fields names in JSON should be same as the parameters name in the Bean. Also all the parameters should have getters and setters. * */ public String convertObjectToJSON(Object object) { DummyBean dummyBean = (DummyBean)object; JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass( DummyBean.class ); JSON jsonString = JSONSerializer.toJSON(object, jsonConfig); return jsonString.toString(); } public static void main(String args[]) throws Exception { new JSONObjectConversion(); } } |