要將數(shù)組元素與key關(guān)聯(lián)起來,可以使用JSONObject類。以下是一個示例:
import org.json.JSONArray;
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
// 創(chuàng)建一個JSONArray對象
JSONArray jsonArray = new JSONArray();
// 向JSONArray中添加元素
jsonArray.put("元素1");
jsonArray.put("元素2");
jsonArray.put("元素3");
// 創(chuàng)建一個JSONObject對象
JSONObject jsonObject = new JSONObject();
// 將JSONArray與key關(guān)聯(lián)起來
jsonObject.put("myKey", jsonArray);
// 輸出結(jié)果
System.out.println(jsonObject.toString());
}
}
在這個示例中,我們首先創(chuàng)建了一個JSONArray對象,并向其中添加了一些元素。然后,我們創(chuàng)建了一個JSONObject對象,并使用put
方法將JSONArray與一個key("myKey")關(guān)聯(lián)起來。最后,我們將整個JSONObject對象轉(zhuǎn)換為字符串并輸出。