Home > Java > javaTutorial > body text

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

WBOY
Release: 2023-09-19 18:37:02
forward
884 people have browsed it

如何使用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>
Copy after login

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
   }
}
Copy after login

Output

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

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template