![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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" ] }
Advertisements