How to convert xml strings to Java objects
This article is to share with you about how to convert xml strings into Java objects, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.
Receive the request from the sender in controller: what is in the @ RequestBody keyword, that is, the @ XmlRootElement//@XmlRootElement keyword of the http request must have public class User implements Serializable {private String userId; private String userName; public String getUserId () {return userId;} public void setUserId (String userId) {this.userId = userId } public String getUserName () {return userName;} public void setUserName (String userName) {this.userName = userName;}} public static String beanToXml (Object obj, Class load) throws JAXBException {JAXBContext context = JAXBContext.newInstance (load); Marshaller marshaller = context.createMarshaller () Marshaller.setProperty (Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setProperty (Marshaller.JAXB_ENCODING, "GBK"); StringWriter writer = new StringWriter (); marshaller.marshal (obj, writer); return writer.toString () } public static Object xmlToBean (String xmlStr, Class load) throws JAXBException, IOException {JAXBContext context = JAXBContext.newInstance (load); Unmarshaller unmarshaller = context.createUnmarshaller (); Object object = unmarshaller.unmarshal (new StringReader (xmlStr)); return object;}
Xml message encryption and decryption:
Private static String decode (String key, String data) {try {byte [] bytes = Base64.getDecoder () .decode (key); byte [] databytes = Base64.getDecoder () .decode (data); Cipher cipher = Cipher.getInstance ("AES"); SecureRandom random = SecureRandom.getInstance ("SHA1PRNG") Random.setSeed (bytes); KeyGenerator keyGen = KeyGenerator.getInstance ("AES"); keyGen.init (128, random); SecretKey secret = keyGen.generateKey (); cipher.init (Cipher.DECRYPT_MODE, secret) Return new String (cipher.doFinal (databytes));} catch (Exception e) {log.debug (e.getMessage ()); return null }} the above is how to convert xml strings into Java objects. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.