XML轉JSON

依賴的包:
org.json.jar,commons-io-2.2.jar

獲取xml文件的InputStream is,使用IOUtils把is轉成String。調用XML的toJSONObject方法獲取JSON對象。
  1. import org.apache.commons.io.IOUtils;
    import org.json.*;

  2. InputStream is = Broadlink.class.getResourceAsStream("broadlink-command-conf.xml");
    String xml;
    try 
    {
        xml = IOUtils.toString(is);
        JSONObject comm = XML.toJSONObject(xml);
        JSONArray commands = comm.getJSONArray("Command");
        for(int i=0;i<commands.length();i++)
         {
             JSONObject jobj = commands.getJSONObject(i);
             JSONObject jo = jobj.getJSONObject("Argument");
             jo.put("api_id", Integer.parseInt(jo.getString("api_id")));
             jobj.put("Argument", jo);
             commandHashMap.put(jobj.getJSONObject("Argument").getString("command"), jobj);
         }

     catch (IOException | JSONException e) 
    {
         e.printStackTrace();
    }

xml文件內容如下:
<Command>
<Argument>
<api_id>1</api_id>
<command>network_init</command>
<license>/Xyap05LJINjNHBJxVNagBIA5eKyT4N0s6w8Mn+z/isCHHw9D56cjeUGKwVc+Qnu6AC0Cv70giQTOv9BqgsQGbg/xTP+gacNT8jgkcGo0cF2Y1vuBzI=</license>
</Argument>
<Retval>
<code>0</code>
<msg>network_init success</msg>
</Retval>
</Command>

<Command>
<Argument>
<api_id>11</api_id>
<command>probe_list</command>
</Argument>
<Retval>
<code>0</code>
<msg>Execute success!</msg>
<list>
<mac></mac>
<type></type>
<name></name>
<lock></lock>
<password></password>
<id></id>
<subdevice></subdevice>
<key></key>
</list>
</Retval>
</Command>
轉換的JSON字串:
{"Command":
[
{"Argument":
{"api_id":"1","command":"network_init","license":"/Xyap05LJINjNHBJxVNagBIA5eKyT4N0s6w8Mn+z/isCHHw9D56cjeUGKwVc+Qnu6AC0Cv70giQTOv9BqgsQGbg/xTP+gacNT8jgkcGo0cF2Y1vuBzI="},
"Retval":
{"code":"0","msg":"network_init success"}},
{"Argument":
{"api_id":"11","command":"probe_list"},
"Retval":
{"list":{"id":"","subdevice":"","name":"","lock":"","mac":"","type":"","password":"","key":""},"code":"0","msg":"Execute success!"}}]}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章