在Java中使用org.json创建一个JSON对象可以按照以下步骤进行:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20210307</version>
</dependency>
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
JSONObject json = new JSONObject();
}
}
json.put("name", "John");
JSONObject address = new JSONObject();
address.put("street", "123 Main St");
address.put("city", "New York");
json.put("address", address);
String jsonString = json.toString();
System.out.println(jsonString);
完整的示例代码如下:
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
JSONObject json = new JSONObject();
json.put("name", "John");
JSONObject address = new JSONObject();
address.put("street", "123 Main St");
address.put("city", "New York");
json.put("address", address);
String jsonString = json.toString();
System.out.println(jsonString);
}
}
这样,你就可以使用org.json在Java中创建一个类似于以下示例的JSON对象:
{
"name": "John",
"address": {
"street": "123 Main St",
"city": "New York"
}
}
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云