我正在学习从xml解析json,并且我解析了它但是当我从xml解析json时,我在我的json中获得新行字符可以有人请建议我如何删除它,这是我的java代码。 公共课Test2 {
private URL url = null;
private InputStream inputStream = null;
private int test = 4;
public void getXMLfromJson() {
try {
url = this.getClass().getClassLoader().getResource("sample.xml");
inputStream = url.openStream();
String xml = IOUtils.toString(inputStream);
org.json.JSONObject JSON = XML.toJSONObject(xml);
String json = JSON.toString(test);
System.out.println(json);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
url = null;
} catch (IOException ex) {
}
}
}
public static void main(String[] args) {
new Test2().getXMLfromJson();
}
}
我正在阅读的Xml文件如下,
<!--?xml version="1.0" encoding="UTF-8"?-->
<catalog>
<book id="bk01">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
<book id="bk02">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.</description>
</book>
</catalog>
这是我的程序的输出,其中我遇到了遇到新行的转义字符和空格
{"catalog": {"book": [
{
"genre": "Computer",
"id": "bk01",
"author": "Gambardella, Matthew",
"title": "XML Developer's Guide",
"price": 44.95,
"publish_date": "2000-10-01",
"description": "An in-depth look at creating applications\n with XML."
},
{
"genre": "Fantasy",
"id": "bk02",
"author": "Ralls, Kim",
"title": "Midnight Rain",
"price": 5.95,
"publish_date": "2000-12-16",
"description": "A former architect battles corporate zombies,\n an evil sorceress, and her own childhood to become queen\n of the world."
}
]}}
我怎样才能逃脱这个\ n新行字符和空格。
答案 0 :(得分:0)
我认为您应该找到一种方法,以便您的XML不具备它们。你上面所做的只是转换,而不是转换。
答案 1 :(得分:0)
只是分享我的解决方案。只需在将其转换为JSON之前替换XML中的换行符。
//to replace line break in XML
public string escapeLineBreak(string myXml) {
if (myXml != null && myXml != "") {
return myXml.Replace("\r\n", "\\n");
} else {
return myXml;
}
}