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

Chuyển XML sang JSON array trong Java (org.json)

JSON là định dạng data-interchange nhẹ, định dạng key-value pair. Có thể chuyển XML sang JSON array dùng org.json.XML class, cung cấp phương thức static XML.toJSONObject() để chuyển XML sang JSON.

Cú pháp

public static JSONObject toJSONObject(java.lang.String string) throws JSONException

Ví dụ minh họa

import org.json.*;

public class ConvertXMLToJSONArrayTest {
    public static String xmlString = ""
        + ""
        + "  tutorialspoint"
        + "  tutorix"
        + "";
    
    public static void main(String[] args) {
        try {
            JSONObject json = XML.toJSONObject(xmlString); // chuyển xml sang json
            String jsonPrettyPrintString = json.toString(4); // json pretty print
            System.out.println(jsonPrettyPrintString);
        } catch(JSONException je) {
            System.out.println(je.toString());
        }
    }
}

Kết quả

{
    "root": {
        "test": [
            {
                "attrib": "jsontext1",
                "content": "tutorialspoint"
            },
            {
                "attrib": "jsontext2",
                "content": "tutorix"
            }
        ]
    }
}

Quy tắc chuyển đổi: Element XML lặp lại cùng tên (như <test> xuất hiện 2 lần) tự động chuyển thành JSONArray. Attribute XML thành property JSON. Text content element thành property "content". Namespace, comment, processing instruction có quy tắc riêng.