【发布时间】:2013-06-01 02:18:14
【问题描述】:
我想在 java 中从 xml 转换为 json 并获得输出。 但是这样做只会转换 xml 中的某些部分,而不是整个 xml。 任何帮助 我的输入 xml 是:
<?xml version="1.0" encoding="UTF-8"?>
<important-data certified="true" processed="true">
<timestamp>232423423423</timestamp>
<authors>
<author>
<firstName>Tim</firstName>
<lastName>Leary</lastName>
</author>
</authors>
<title>Flashbacks</title>
<shippingWeight>1.4 pounds</shippingWeight>
<isbn>978-0874778700</isbn>
</important-data>
我的代码是: 包 com.discursive.answers;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import net.sf.json.JSON;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;
import org.json.XML;
public class ConvertXMLtoJSON {
public static int PRETTY_PRINT_INDENT_FACTOR = 4;
public static String TEST_XML_STRING = "<?xml version=\"1.0\" ?>" +
"<test attrib=\"moretest\">" +
"Turn this to JSON</test>";
public static void main(String[] args) {
new ConvertXMLtoJSON();
}
public ConvertXMLtoJSON() {
try {
InputStream is = ConvertXMLtoJSON.class.getResourceAsStream("sample-xml.xml");
if (is != null) {
String xml = IOUtils.toString(is);
JSON json = XMLSerializer.readObject(xml);
System.out.println(json.toString().split(",").length);
for(int i= 0 ;i < json.toString().split(",").length; i ++)
System.out.println(json.toString().split(",")[i]);
} else {
System.out.println("Checkpoint 1");
}
} catch (java.io.IOException ioe) {
ioe.printStackTrace();
}
}
应用上面提到的 xml 和代码,我得到的输出为:
{"timestamp":"232423423423"
"authors":"\n\t\t\n\t\t\tTim\n\t\t\tLeary\n\t\t\n\t"
"title":"Flashbacks"
"isbn":"978-0874778700"
"shippingWeight":"1.4 pounds"}
应该在哪里:
{
"@certified": "true",
"@processed": "true",
"timestamp": "232423423423",
"authors": [ {
"firstName": "Tim",
"lastName": "Leary"
}],
"title":
"Flashbacks",
"shippingWeight": "1.4 pounds",
"isbn": "978-0874778700"
}
我应该做哪些更改才能获得所需的输出?
【问题讨论】:
-
在发布之前我已经看过所述示例。但是在所述示例中,xml 是字符串格式..我想通过 sample-xml.xml 文件给出它。
-
StackOverflow 不是来教你计算机编程的基础知识的;将文件读入字符串不应该是一个陌生的概念。除此之外,忽略古老的 json.org 代码现在很少是最佳选择,关键是:您需要一个 XML 库和一个 JSON 库。反序列化 XML,然后将其序列化为 JSON。