【发布时间】:2015-02-15 20:45:15
【问题描述】:
我想将一个 dom 节点列表转换为一个 json 数组并将结果发送给一个 REST 客户端:
xml的每个节点代表如下:
<A NAME="x" COUNT="y">
<B KEY="z1" VALUE="z2"/>
<B KEY="z3" VALUE="z4"/>
</A>
我希望输出一个对象数组,其中每个对象如下所示:
{"NAME":"x",
"COUNT":"y",
"B": [ {"KEY": "z1, VALUE:"z2"},
{"KEY":"z3", VALUE:"z4"} ]
}
我尝试使用 GSON 库:
package com.a;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class Test {
private static final String XPATH = "/A/B";
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
File f = new File("C:/Users/abc/Desktop/a.xml");
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse(f);
XPath xPath = XPathFactory.newInstance().newXPath();
NodeList nodeList = (NodeList) xPath.compile(XPATH).evaluate(xmlDocument, XPathConstants.NODESET);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonOutput = gson.toJson(nodeList);
System.out.println(jsonOutput);
}
}
但我遇到了错误
线程“主”java.lang.StackOverflowError 中的异常
java.lang.StringBuffer.append(StringBuffer.java:224) 在
java.io.StringWriter.write(StringWriter.java:84) 在
com.google.gson.stream.JsonWriter.newline(JsonWriter.java:569) 在
com.google.gson.stream.JsonWriter.beforeName(JsonWriter.java:586)
如何修复此代码?
因为可以将整个 xml 转换为 json (Quickest way to convert XML to JSON in Java)
我假设可以将 dom 节点转换为 json。这里有什么问题?
【问题讨论】: