依赖的包:
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.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>
<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="},
[
{"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!"}}]}