为JAXB和response设置编码,解决wechat4j中文乱码
1 https://blog.youkuaiyun.com/qing_gee/article/details/52788962
2 在web环境中使用JAXB技术对XML文件进行序列化和反序列化时如何避免乱码
http://www.cnblogs.com/hzhuxin/archive/2012/10/29/2745293.html
注:通过System.getProperty("file.encoding")可以获知当前执行环境的编码。通过该属性发现有时WEB环境下和测试用例环境下编码会不一样,这就会导致有时测试正常,实际环境下运行出现乱码的原因。
总结:掌握两个原则(1)用JAXB转XML为对象时,会转对象编码为本地JAVA环境的字符编码
(2) 用JAXB转对象为XML时,默认会转为UTF-8编码,所以要保证不出乱码,转的时候应指定转为与本地JAVA环境相同的字符编码,或者保证在转的时候同时指定文件编码和转换的输出流编码一致
3 http://www.cnblogs.com/zyfxlv/archive/2013/01/23/2872955.html
对象转为xml的方法:objToXmlString
public static <T> String objToXmlString(T obj) throws JAXBException {
JAXBContext jc = JAXBContext.newInstance(obj.getClass());
Marshaller m = jc.createMarshaller();
m.setProperty("jaxb.formatted.output", true);
ByteArrayOutputStream out = new ByteArrayOutputStream();
Result result = new StreamResult(out);
m.marshal(obj, result);
//转码
byte[] bystr = out.toByteArray();
String str = "";
try {
str = new String(bystr,"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
StringBuffer sb = new StringBuffer(str.replace("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>", ""));
//log.error("JAXB transform object to string without version: "+ sb.toString());
return sb.toString();
}
第一种转码方式(在网上找的): m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");但在我这个项目中不起作用,不知为什么
第二种:上面方法中转码那一步,如果不转码,直接这么写的话,StringBuffer sb = new StringBuffer(new String(out.toByteArray()).replace("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>", ""));取到的中文是乱码
4 java中文乱码字符集解决大全
https://blog.youkuaiyun.com/wo6925371/article/details/5996079
5 处理中文乱码和部分乱码
https://blog.youkuaiyun.com/lhzjj/article/details/41802761
清晰图片见如下