Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

แปลง XML เป็น JSON Array ใน Java ด้วย org.json.XML

JSON เป็น Data-Interchange Format แบบ Lightweight Key-Value Pair แปลง XML เป็น JSON Array ได้ด้วยคลาส org.json.XML มี Static Method XML.toJSONObject() แปลง XML String เป็น JSONObject

Syntax

public static JSONObject toJSONObject(String string) throws JSONException

ตัวอย่าง: Convert XML to JSON Array

import org.json.*;

public class ConvertXMLToJSONArrayTest {
    public static String xmlString = ""
        + ""
        + "tutorialspoint"
        + "tutorix"
        + "";
    
    public static void main(String[] args) {
        try {
            JSONObject json = XML.toJSONObject(xmlString);  // Convert XML to JSON
            String jsonPrettyPrintString = json.toString(4);  // Pretty Print
            System.out.println(jsonPrettyPrintString);
        } catch (JSONException je) {
            System.out.println(je.toString());
        }
    }
}

ผลลัพธ์

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

สังเกต: XML Element ที่ซ้ำกัน (<test> 2 ตัว) จะกลายเป็น JSON Array อัตโนมัติ Attributes กลายเป็น Fields, Text Content กลายเป็น content Field

Dependency: org.json:json