How do you set a key in a JSONObject in Java?
In Java, you can use the `put()` method to set key-value pairs in a JSON object. Here is an example:
import org.json.JSONObject;public class Main {
public static void main(String[] args) {
// 创建一个空的JSON对象
JSONObject jsonObject = new JSONObject();
// 设置键值对
jsonObject.put("key1", "value1");
jsonObject.put("key2", "value2");
// 打印JSON对象
System.out.println(jsonObject);
}
}
Running the above code will produce the following results:
{"key1":"value1","key2":"value2"}
In this example, we are using the `put()` method to set key-value pairs. The first parameter is the key and the second parameter is the value.