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;
}
暫時沒找到支持存在這種字符能解析的方法