Parsing JSON Object – Java
In Java, JSON object can be directly converted to String and we can do String manipulations. Also, the JSON Object created can be parsed using the field name present in JSON Object.
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 |
import org.json.simple.JSONObject; class JSONBuilder { public static void main(String[] args) { JSONObject jsonObject = new JSONObject(); jsonObject.put("names", "testjsonuser3"); jsonObject.put("actions", "IllustrateJSONObjectInScript"); jsonObject.put("logincount", "3"); System.out.print(jsonObject); StringWriter out = new StringWriter(); jsonObject.writeJSONString(out); String jsonString = out.toString(); System.out.println("JSON Converted to String:"); System.out.print(jsonString); System.out.println("JSONObject Values:"); System.out.print("names:" + jsonObject.get("names")); System.out.print(",actions:" + jsonObject.get("actions")); System.out.print(",logincount:" + jsonObject.get("logincount")); } } |
Result:
1 2 3 4 |
JSON Converted to String: {“names”: “testjsonuser3”, “actions”:”IllustrateJSONObjectInScript”, “logincount”:3} JSONObject Values: names:testjsonuser3,actions: IllustrateJSONObjectInScript,logincount: 3 |
The “names”, “actions” and “logincount” values is displayed by parsing the object jsonObject directly in java as explained.