加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

XML转JSON

发布时间:2020-12-16 05:50:46 所属栏目:百科 来源:网络整理
导读:依赖的包: org.json.jar,commons-io-2.2.jar 获取xml文件的InputStream is,使用 IOUtils把is转成String 。调用XML的 toJSONObject方法获取JSON对象。 import org.apache.commons.io.IOUtils; import org.json.*; InputStream is = Broadlink.class.getRes
依赖的包:
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>

<api_id>11</api_id>
<command>probe_list</command>
<msg>Execute success!</msg>
<list>
<mac></mac>
<type></type>
<name></name>
<lock></lock>
<password></password>
<id></id>
<subdevice></subdevice>
<key></key>
</list>
转换的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!"}}]}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读