How to add elements to a JSONObject in Java?

To add elements to a JsonObject, you can use the put method. Here are the specific steps:

  1. Create an empty JsonObject object.
JsonObject jsonObject = new JsonObject();
  1. Add elements using the put method. The put method takes two parameters: the first parameter is the key and the second parameter is the value.
jsonObject.put("key1", "value1");
jsonObject.put("key2", "value2");
  1. The added elements can be of any data type, such as strings, numbers, booleans, etc.
jsonObject.put("key3", 123);
jsonObject.put("key4", true);

Here is the complete example code:

import org.json.JSONObject;

public class Main {
    public static void main(String[] args) {
        // 创建一个空的JsonObject对象
        JSONObject jsonObject = new JSONObject();

        // 添加元素
        jsonObject.put("key1", "value1");
        jsonObject.put("key2", "value2");
        jsonObject.put("key3", 123);
        jsonObject.put("key4", true);

        // 打印JsonObject
        System.out.println(jsonObject.toString());
    }
}

The output results:

{"key1":"value1","key2":"value2","key3":123,"key4":true}
bannerAds