Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Thêm JSONArray vào JSONObject trong Java (org.json)

JSONObject parse text từ String tạo object giống map. JSONArray parse text từ String tạo object giống vector. Có thể thêm JSONArray vào JSONObject bằng cách tạo JSONArray với vài item và thêm mảng này vào phương thức put() của JSONObject.

Cú pháp

public JSONObject put(java.lang.String key, java.util.Collection<?> value) throws JSONException

Ví dụ minh họa

import org.json.*;

public class AddJSONArrayTest {
    public static void main(String[] args) throws JSONException {
        JSONArray array = new JSONArray();
        array.put("INDIA");
        array.put("AUSTRALIA");
        array.put("ENGLAND");
        
        JSONObject obj = new JSONObject();
        obj.put("COUNTRIES", array);
        System.out.println(obj);
    }
}

Kết quả

{"COUNTRIES":["INDIA","AUSTRALIA","ENGLAND"]}

Mở rộng: put() nạp chồng cho nhiều kiểu: put(String, boolean), put(String, int), put(String, double), put(String, Object), put(String, Map), put(String, Collection), put(String, JSONArray). JSONObject cũng hỗ trợ accumulate(key, value) để thêm nhiều giá trị cho cùng key (tự tạo array).