JSONObject obj = new JSONObject(); obj.put("name", "John"); obj.put("age", 30); obj.put("city", "New York"); System.out.println(obj);
{"name":"John","age":30,"city":"New York"}
String jsonString = "{\"name\":\"John\",\"age\":30}"; JSONObject obj = JSONObject.fromObject(jsonString); String name = obj.getString("name"); int age = obj.getInt("age"); System.out.println(name + " is " + age + " years old.");
Person p = new Person("John", 30); JSONObject obj = JSONObject.fromObject(p); System.out.println(obj);This code creates a Java object of type Person and converts it into a JSONObject using the fromObject() method. The resulting JSON object represents the data in the Person object. Overall, the net.sf.json package library provides a convenient way to work with JSON data in Java, and the JSONObject element is a key component of this library.