在使用JSon-Lib庫進行XML2JSon的轉換時,在JUnit測試時沒有什么問題,但是在Tomcat里面跑的時候,拋出了下面的異常,查找了google,發現關於這方便的文章比較少,即使有,也需要翻牆去查找,於是就自己記錄下來,以便后面的人查找翻遍。
net.sf.json.JSONException: nu.xom.ParsingException: Element type "鍥句功嫻侀" must be followed by either attribute specifications, ">" or "/>". at line 1, column 46
找到最原始的一個文章連接是下面的鏈接,上面說明了,在不同的環境上面,在轉換中文的時候,出現了使用不同的編碼集導致了問題。
http://www.codeweblog.com/transfer-element-type-must-be-followed-by-either-attribute-specifications/
知道了問題的所在,但是依然不知道如何解決。於是又搜索到了一位大俠的文章《[轉]Element Type Must Be Followed By Either Attribute Specifications, “>”》
http://newwhx2011.iteye.com/blog/1121201
在這片文章里面,明確說了【關於new XMLSerializer().readFromFile()在讀取文件內容時,從字節流轉換為字符流時並沒有指定編碼,此處應該是json-lib代碼的Bug。】,於是查看了XMLSerializer的代碼,發現確實是在轉換的時候,沒有指定編碼,於是按照他提供的思路,進行了編碼,也就是自己指定編碼處理。
原來的代碼:
1 public static String xml2json(File xmlFile) throws Exception { 2 XMLSerializer xmlSerializer = new XMLSerializer(); 3 JSON json = xmlSerializer.readFromFile(xmlFile); 4 return json.toString(2); 5 }
更改后的代碼,也就是把原來XMLSerializer里面的代碼copy出來,同時加了一個編碼的設置,現在一切都正常了
public static String xml2json(File xmlFile) throws Exception { JSON json = readFromStream(new FileInputStream(xmlFile)); return json.toString(2); } public static JSON readFromStream(InputStream stream) throws Exception { StringBuffer xml = new StringBuffer(); BufferedReader in = new BufferedReader(new InputStreamReader(stream,"UTF-8")); String line = null; while ((line = in.readLine()) != null) { xml.append(line); } XMLSerializer xmlSerializer = new XMLSerializer(); return xmlSerializer.read(xml.toString()); }
