我正在使用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();
}
它工作正常,除了反序列化时将é字符转换为‰(它们已序列化,并且生成的XML文件显示正确的字符)。我知道这与字符编码(UTF8与ISO-8859-2)有关,但是我不知道如何将其连接到Jackson的反序列化机制中。
任何帮助将不胜感激!
谢谢
答案 0 :(得分:0)
我最终放弃了Jackson,转而使用java.beans.XMLDecoder;
类。使用此方法时,保留加重字符。