【发布时间】:2017-12-12 22:05:45
【问题描述】:
我必须将 StackExchange 的数据集转换为 Json 文件,所以我尝试了这个-
public class Parser {
public static int PRETTY_FACTOR=4;
public static void main(String[] args) throws Exception {
String fileName = "/home/dipannoy/Desktop/stackexchange/android/posthistory.json";
String path= "/home/dipannoy/Desktop/stackexchange/android/PostHistory.xml";
try {
StringBuilder builder = new StringBuilder();
FileInputStream inputStream = null;
Scanner sc = null;
try {
inputStream = new FileInputStream(path);
sc = new Scanner(inputStream, "UTF-8");
while (sc.hasNextLine()) {
String line = sc.nextLine();
builder.append(line);
}
if (sc.ioException() != null) {
throw sc.ioException();
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (sc != null) {
sc.close();
}
}
String xml = builder.toString();
JSONObject jsonObj = XML.toJSONObject(xml);
FileWriter fileWriter = new FileWriter(fileName);
BufferedWriter bufferedWriter =new BufferedWriter(fileWriter);
bufferedWriter.write(jsonObj.toString());
bufferedWriter.flush();
bufferedWriter.close();
fileWriter.close();
}
catch(IOException ex) {
System.out.println(
"Error writing to file '"
+ fileName + "'");
} catch(Exception e) {
e.printStackTrace();
}
}
}
但它在 jsonObj.toString() 出现错误。
示例 xml 是 -
<comments>
<row Id="1" PostId="1" Score="4" Text="Did I just place the first upvote? Congrats on getting this site off the ground!" CreationDate="2016-01-12T18:47:12.573" UserId="23"/>
</comments>
我曾尝试使用 Gson,但未能将 GSONObject 转换为 GsonObject,因为 GsonParser 需要 GSONObject 的 toString() 方法来创建 OutOfMemoryError。有人可以帮忙解决这个问题吗?
【问题讨论】:
-
你知道你正在将整个数据集加载到内存中,因此
OutOfMemoryError?除了为您编写代码之外,我不确定任何人都可以做些什么来提供帮助。查找 StAX 解析器。 -
如果它只是在 JSONObject.toString 上失败(XML 和 JSON 对象图已经完全加载到内存中,等等),它应该可以使用 streaming writer - ref。 stackoverflow.com/questions/21577848/streaming-to-write-json 流式编写器不会首先调用 to-string,因为那样会破坏流式传输的目的。即使(Gson 的实现)不能直接从 JSONObject 使用,也应该可以遍历对象图的各个部分并通过流式编写器分别发出这些部分。当然,从端到端流式传输..
标签: java json xml out-of-memory