我正在使用 jackson 使用以下代码序列化 XML 文件中的客户实体:
XmlMapper mapper = new XmlMapper();
String exportPath = System.getenv("TFH_HOME") + File.separator + "data" + File.separator + "XML" + File.separator;
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
List<Customer> customers = customerService.findAllExplicit();
customers.forEach((customer) ->
{
try
{
mapper.writeValue(new File(exportPath + "customers" + File.separator + customer.getCustomerNumber() + ".xml"), customer);
}
catch (IOException ex)
{
logger.error("Error serializing customer " + customer.toString() + " : " + ex.getMessage());
}
});
这可以完美运行,并为每个客户创建一个包含所有数据的 XML 文件。问题是该数据是法语的,因此包含重音字符,例如 é。这是我用来反序列化所述客户的代码:
public void importCustomers()
{
File customerFolder = new File(exportPath + "customers");
for (File customerFile : customerFolder.listFiles())
{
try
{
String customerXML = inputStreamToString(new FileInputStream(customerFile));
Customer customer = mapper.readValue(customerXML, Customer.class);
customer.setId(null);
customerService.save(customer);
}
catch (IOException ex)
{
logger.error("Error importing customer : " + ex.getMessage());
}
}
}
private static String inputStreamToString(InputStream is) throws IOException
{
StringBuilder sb = new StringBuilder();
String line;
try (BufferedReader br = new BufferedReader(new InputStreamReader(is)))
{
while ((line = br.readLine()) != null)
{
sb.append(line);
}
}
return sb.toString();
}
它完美地工作,除了 é 字符在反序列化时转换为 É(它们被序列化 OK 并且生成的 XML 文件显示正确的字符)。我知道这与字符编码(UTF8 与 ISO-8859-2)有关,但我不知道如何将其连接到 Jackson 反序列化机制中。
任何帮助,将不胜感激!
谢谢