Home  >  Article  >  Java  >  How to add elements to JSON object using JSON-lib API in Java?

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

WBOY
WBOYforward
2023-09-19 18:37:02883browse

如何使用Java中的JSON-lib API向JSON对象添加元素?

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.

Syntax

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

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

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete