import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
JSONObject jsonObject = new JSONObject();
try {
// 添加字符串属性
jsonObject.put("name", "John Doe");
// 添加整数属性
jsonObject.put("age", 25);
// 添加布尔属性
jsonObject.put("isMarried", false);
// 添加数组属性
JSONArray jsonArray = new JSONArray();
JSONObject arrayObj1 = new JSONObject();
arrayObj1.put("id", 1);
arrayObj1.put("name", "Apple");
JSONObject arrayObj2 = new JSONObject();
arrayObj2.put("id", 2);
arrayObj2.put("name", "Banana");
jsonArray.put(arrayObj1);
jsonArray.put(arrayObj2);
jsonObject.put("fruits", jsonArray);
System.out.println(jsonObject.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
在以上示例中,我们创建了一个JSON对象,包含了名为"name"、"age"和"isMarried"的属性,分别为字符串、整数和布尔类型。还创建了一个名为"fruits"的属性,它是一个JSON数组。JSON数组中包含了两个JSON对象,每个对象都有"id"和"name"属性。最后,我们通过调用toString()
方法将JSON对象转换为字符串并打印出来。
执行以上代码,输出的结果为:
{
"name":"John Doe",
"age":25,
"isMarried":false,
"fruits":[
{
"id":1,
"name":"Apple"
},
{
"id":2,
"name":"Banana"
}
]
}