How to add elements to JSON Object using JSON-lib API in Java?


The JSON-lib is a Java library for serializing and de-serializing java beans, maps, arrays, and collections in JSON format. We can add elements to the JSON object using the element() method of JSONObject class. We need to download all the dependent jars like json-lib.jar, ezmorph.jar, commons-lang.jar, commons-collections.jar, commons-beanutils.jar, and commons-logging.jar and can import net.sf.json package in our java program to execute it.

Syntax

public JSONObject element(String key, Object value) - put a key/value pair in the JSONObject

Example

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
   }
}

Output

{
   "name": "Raja Ramesh",
   "age": 30,
   "address": "Hyderabad",
   "contact numbers": [
      "9959984000",
      "7702144400",
      "7013536200"
   ]
}

Updated on: 08-Jul-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements