Home >Java >javaTutorial >How to add elements to JSON object using JSON-lib API in Java?
JSON-lib is a Java library for serializing and deserializing java beans, maps, arrays and Collection in JSON format. We can add elements to a JSON object using the element() method of the JSONObject class. We need to download all dependent jars, such as json-lib.jar, ezmorph.jar, commons-lang.jar, commons-collections.jar commons-beanutils.jar, and commons-logging.jar, and the net.sf.json package can be imported in our java program to execute it.
public JSONObject element(String key, Object value) - put a key/value pair in the JSONObject<strong> </strong>
import java.util.Arrays; import net.sf.json.JSONObject; public class JsonAddElementTest { public static void main(String[] args) { JSONObject jsonObj = new JSONObject() .element("name", "Raja Ramesh") .element("age", 30) .element("address", "Hyderabad") .element("contact numbers", Arrays.asList("9959984000", "7702144400", "7013536200")); System.out.println(jsonObj.toString(3)); //pretty print JSON } }
{ "name": "Raja Ramesh", "age": 30, "address": "Hyderabad", "contact numbers": [ "9959984000", "7702144400", "7013536200" ] }
The above is the detailed content of How to add elements to JSON object using JSON-lib API in Java?. For more information, please follow other related articles on the PHP Chinese website!