org.json - XML



XML 類提供將 XML 文字轉換為 JSONObject, 反之亦然的方法。

示例中涵蓋以下方法。

  • toJSONObject(String) - 將 XML 轉換為 JSONArray 物件。

  • toString(JSONObject) - 從 JSONObject 物件獲取 XML。

示例

import org.json.JSONObject;
import org.json.XML;

public class JSONDemo {
   public static void main(String[] args) { 
      JSONObject jsonObject = new JSONObject();
      jsonObject.put("Name", "Robert");
      jsonObject.put("ID", 1);
      jsonObject.put("Fees", new Double(1000.21));
      jsonObject.put("Active", new Boolean(true));
      jsonObject.put("Details", JSONObject.NULL);

      //Convert a JSONObject to XML
      String xmlText = XML.toString(jsonObject);
      System.out.println(xmlText);

      //Convert an XML to JSONObject
      System.out.println(XML.toJSONObject(xmlText));
   }
}

輸出

<Active>true</Active><Details>null</Details><ID>1</ID><Fees>1000.21</Fees><Name>Robert</Name>
{"Active":true,"Details":null,"ID":1,"Fees":1000.21,"Name":"Robert"}
廣告