微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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>

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。