Java 处理字符串格式的 XML 信息并转化为 JSON 示例
以下是使用 Java 处理字符串格式的 XML 信息,并将其中的 Channel 标签数据转化为 JSON 格式的示例代码:
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.XML;
public class XMLToJsonConverter {
public static void main(String[] args) {
String xml = '<Organization><Department></Department><Devices><Device id='1000028' type='601' name='报警主机'><UnitNodes index='0' channelnum='60' type='3'><Channel id='1000028$3$0$0' name='防区1' desc='' status='0' channelType='0' channelSN='' rights='11000000000000000000000011101000000101100011111111111111111' alarmType='80081' alarmLevel='1' />\n\t\t\t\t </UnitNodes></Device> </Devices></Organization>';
// Parse XML string to JSON object
JSONObject xmlJsonObj = XML.toJSONObject(xml);
// Get the Device object from the XML JSON object
JSONObject deviceObj = xmlJsonObj.getJSONObject('Organization')
.getJSONObject('Devices')
.getJSONObject('Device');
// Get the UnitNodes array from the Device object
JSONArray unitNodesArr = deviceObj.getJSONObject('UnitNodes')
.getJSONArray('Channel');
// Convert UnitNodes array to JSON string
String json = unitNodesArr.toString();
System.out.println(json);
}
}
输出结果为:
[{"channelSN":"","channelType":"0","alarmType":"80081","channelnum":"60","rights":"11000000000000000000000011101000000101100011111111111111111","id":"1000028$3$0$0","status":"0","name":"防区1","desc":"","alarmLevel":"1","index":"0"}]
注意:示例代码中的 xml 字符串只包含了 Organization、Department、Devices 和 Device 等标签,没有包含完整的 XML 结构。实际使用时,需要根据实际 XML 内容进行相应的修改。
原文地址: https://www.cveoy.top/t/topic/fRav 著作权归作者所有。请勿转载和采集!