我有一些代码将地图编码为XML,然后解码此XML。当地图值只有ASCII字符时,它会按预期工作,否则会崩溃。如何使其与Unicode字符一起使用?请记住,我有使用此方案编码的遗留数据,因此不能选择切换到完全不同的编码方法。
String firstName = "Влади́мир";
Map<String, Object> map = new HashMap<String, Object>();
map.put("firstName", firstName);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
XMLEncoder encoder = new XMLEncoder(outputStream);
encoder.writeObject(map);
encoder.close();
String serialized = outputStream.toString("UTF-8");
System.out.println(serialized); // output looks OK
XMLDecoder decoder = new XMLDecoder(new StringInputStream(serialized));
Map<String, Object> mapOut = (Map<String, Object>) decoder.readObject(); // exception!
错误:
org.xml.sax.SAXParseException: An invalid XML character (Unicode: 0x12) was
found in the element content of the document.
Continuing ...
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at com.sun.beans.ObjectHandler.dequeueResult(ObjectHandler.java:139)
at java.beans.XMLDecoder.readObject(XMLDecoder.java:206)