xml文本转Java对象
- 开源代码
- 2025-07-21 19:17:50

Java对象转String public static String toData(Object object) throws Exception { JAXBContext jc = JAXBContext.newInstance(object.getClass()); Marshaller m = jc.createMarshaller(); StringWriter output = new StringWriter(2048); m.marshal(object, output); String data = output.toString(); return data; } xmlString转Java对象
使用这个解析会面临一个问题,如果这个xmlString存在一些特殊字符,但是在运行过程中能被识别成Unicode转义字符,在IDEA中字符串标识是乱码,解析时会报错。如:\u0001、\u0002直接在IDEAJava定义字符串正常,进入txt文本则是乱码,控制台打印也是乱码;\u00a0在IDEAJava定义字符串即乱码,txt也是乱码,解析成文本时就不会有问题。
public static Object xmlToObject(String data,Class<?> load) throws JAXBException { JAXBContext context = JAXBContext.newInstance(load); Unmarshaller unmarshaller = context.createUnmarshaller(); Object object = unmarshaller.unmarshal(new StringReader(data)); return object; }暂时没找到支持存在这种字符能解析的方法
xml文本转Java对象由讯客互联开源代码栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“xml文本转Java对象”