In below example, it writes JSON data via JSONObject and JSONArray, and save it into a file named “test.json“ using JSON.simple, a simple Java library for JSON processing.
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 |
import java.io.FileWriter; import java.io.IOException; import org.json.simple.JSONArray; import org.json.simple.JSONObject; public class JsonSimpleExample { public static void main(String[] args) { JSONObject obj = new JSONObject(); obj.put("name", "prasanna"); obj.put("age", new Integer(25)); JSONArray list = new JSONArray(); list.add("msg 1"); list.add("msg 2"); list.add("msg 3"); obj.put("messages", list); try { FileWriter file = new FileWriter("c:\\test.json"); file.write(obj.toJSONString()); file.flush(); file.close(); } catch (IOException e) { e.printStackTrace(); } System.out.print(obj); } } |
Output: (see content of file “test.json”)