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!"}}]}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值