在使用Java将方括号从XML转换后添加到JSON时,可以按照以下步骤进行操作:
以下是一个示例代码片段,用于演示如何将方括号从XML转换后添加到JSON:
import org.json.JSONArray;
import org.json.JSONObject;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;
public class XMLtoJSON {
public static void main(String[] args) {
String xmlString = "<root><name>John</name><age>30</age></root>";
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xmlString)));
JSONObject json = new JSONObject();
processNode(doc.getDocumentElement(), json);
System.out.println(json.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
private static void processNode(Node node, JSONObject json) {
if (node.getNodeType() == Node.ELEMENT_NODE) {
if (node.hasChildNodes()) {
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE) {
JSONObject childJson = new JSONObject();
processNode(child, childJson);
json.put(child.getNodeName(), childJson);
} else if (child.getNodeType() == Node.TEXT_NODE) {
json.put(child.getNodeName(), child.getTextContent());
}
}
}
} else if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
json.put(node.getNodeName(), node.getNodeValue());
}
}
}
这个示例代码将XML字符串 <root><name>John</name><age>30</age></root>
转换为JSON格式。请注意,示例代码中的 JSON 库使用的是 Java 的 JSON.org 库,你也可以根据个人喜好使用其他 JSON 库。
推荐腾讯云相关产品和产品介绍链接地址:
请注意,该示例代码中的产品链接是虚构的,你可以根据实际需求和项目要求选择适合的云计算品牌商和产品。
领取专属 10元无门槛券
手把手带您无忧上云