我必须将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
方法。任何人都可以帮忙吗?
[有一个带有静态方法underscore-java的U.xmlToJson(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>
输出:
{
"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",
"-self-closing": "true"
}
},
"#omit-xml-declaration": "yes"
}