我有如下 SOAP 响应。我想遍历 soap 消息并以 JSONArray 格式获取 listMetadataResponse 标记中的数据。这是我的示例 SOAP 响应:
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns="http://soap.sforce.com/2006/04/metadata">
<soapenv:Body>
<listMetadataResponse>
<result>
<createdById>00528000001m5RRAAY</createdById>
<createdByName>Hariprasath Thanarajah</createdByName>
<createdDate>1970-01-01T00:00:00.000Z</createdDate>
<fileName>objects/EmailMessage.object</fileName>
<fullName>EmailMessage</fullName>
<id />
<lastModifiedById>00528000001m5RRAAY</lastModifiedById>
<lastModifiedByName>Hariprasath Thanarajah</lastModifiedByName>
<lastModifiedDate>1970-01-01T00:00:00.000Z</lastModifiedDate>
<namespacePrefix />
<type>CustomObject</type>
</result>
<result>
<createdById>00528000001m5RRAAY</createdById>
<createdByName>Hariprasath Thanarajah</createdByName>
<createdDate>1970-01-01T00:00:00.000Z</createdDate>
<fileName>objects/EmailMessage.object</fileName>
<fullName>EmailMessage</fullName>
<id />
<lastModifiedById>00528000001m5RRAAY</lastModifiedById>
<lastModifiedByName>Hariprasath Thanarajah</lastModifiedByName>
<lastModifiedDate>1970-01-01T00:00:00.000Z</lastModifiedDate>
<namespacePrefix />
<type>CustomObject</type>
</result>
</listMetadataResponse>
</soapenv:Body>
</soapenv:Envelope>
我想将每个结果节点作为 JSONObject 获取,每个属性节点和值作为 JSON 中的键值对。因此,在这种情况下,我希望结果作为 JSONArray,其中包含两个结果 JSONObject。
我试过这段代码。我正在获取节点名称,但没有获取节点值。
private static Document loadXMLString(String response) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(response));
return db.parse(is);
}
public static JSONArray getFullData(String tagName, String request) throws Exception {
JSONArray resultArray = new JSONArray();
Document xmlDoc = loadXMLString(request);
NodeList nodeList = xmlDoc.getElementsByTagName("*");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
if (node.getNodeName().equals("result")) {
JSONObject rootObject = new JSONObject();
NodeList childNodeList = nodeList.item(i).getChildNodes();
for (int j = 0; j < childNodeList.getLength(); j++) {
node = childNodeList.item(i);
rootObject.put(node.getNodeName(), node.getNodeValue());
}
resultArray.put(rootObject);
}
}
}
}
最佳答案
您可以通过 STLeary 使用 JSON-java 库。
您可以使用以下代码将 XML 字符串转换为 JSONObject。
JSONObject 数据 = XML.toJSONObject(xmlString);
您可以在这里找到更多相关信息:JSON-java
关于java - 将 SOAP 响应转换为 JSONArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45366111/