xml文本转Java对象

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也是乱码,解析成文本时就不会有问题。
xml文本转Java对象_第1张图片

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对象_第2张图片
暂时没找到支持存在这种字符能解析的方法

你可能感兴趣的:(xml,java,开发语言)