Interconversion between xml and java objects based on xstream annotation

       In the actual development of interface communication, the interaction between two systems is often encountered using XML format. There are many methods used by clients of communication.

1. Use JAXB or XStream to convert Java objects to XML. For example, use XStream:

    Maven dependencies:

<dependency>
  <groupId>com.thoughtworks.xstream</groupId>
  <artifactId>xstream</artifactId>
  <version>1.4.7</version>
</dependency>

 

    POJO object 1:

import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
@XStreamAlias("request")
public class TradeFlow {
	@XStreamAlias("seriId")
	private String seriId = "1";
	
	@XStreamAlias("parterId")
	private String parterId = "2";
	
	@XStreamAlias("pointSize")
	private String pointSize = "3";
	
	@XStreamAlias("unitId")
	private String unitId = "4";
	
	@XStreamAlias("validateStr")
	private String validateStr = "5";
	
	@XStreamAlias("phones")
        private List<Phone> phones;
	
	@XStreamAlias("telPhones")
	private List<String> telPhones;
	
	@XStreamImplicit(itemFieldName = "telphone2")
	private List<String> telPhones2;
	//Omit get/set methods for all properties
}

   

   POJO object 2:

import com.thoughtworks.xstream.annotations.XStreamAlias;
@XStreamAlias("phone")
public class Phone {
	@XStreamAlias("msisdn")
	private String msisdn;
	//Omit get/set methods for all properties
}

 

    testing method:

public static void main(String[] args) {
	TradeFlow tradeFlow = new TradeFlow();
        XStream xstream = new XStream();  
        xstream.processAnnotations(TradeFlow.class);
        
        List<Phone> array = new ArrayList<Phone>();
        Phone phone = new Phone();
        phone.setMsisdn("13000000000");
        array.add(phone);
        tradeFlow.setPhones(array);
        
        List<String> telArray = new ArrayList<String>();
        telArray.add("0571-88000000");
        telArray.add("0571-88111111");
        tradeFlow.setTelPhones(telArray);
        
        tradeFlow.setTelPhones2(telArray);
        
        System.out.println(xstream.toXML(tradeFlow));
        
        String xml = xstream.toXML(tradeFlow);//Object conversion XML string
        TradeFlow test = (TradeFlow)xstream.fromXML(xml);//XML string conversion object
        System.out.println(test.getParterId());
}

 

    The result is as follows:

<request>
  <seriId>1</seriId>
  <parterId>2</parterId>
  <pointSize>3</pointSize>
  <unitId>4</unitId>
  <validateStr>5</validateStr>
  <phones>
    <phone>
      <msisdn>13000000000</msisdn>
    </phone>
  </phones>
  <telPhones>
    <string>0571-88000000</string>
    <string>0571-88111111</string>
  </telPhones>
  <telphone2>0571-88000000</telphone2>
  <telphone2>0571-88111111</telphone2>
</request>

   Notice:

   1. The underscore "_" is special in xstream and is used as an escape character, so it is recommended not to use the underscore as the node name in xml in practical applications.

   

   The solution was searched online as follows: http://www.iteye.com/problems/94338

   2. If the parameter value in the POJO object is NULL, the node will be automatically filtered out during xstream rendering. So if you need to display the node, you must assign the corresponding null value (for example: initialize an empty array, empty string).

 

   Comparison between JAXB and XStream : http://www.blogjava.net/ldd600/archive/2009/03/04/257832.html

   For other annotations, please refer to:

   http://liuzidong.iteye.com/blog/1059861

   http://www.cnblogs.com/hoojo/archive/2011/04/22/2025197.html

 

Second, use jdom to read the xml file or string, and then operate on the node:

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Xml2StrReader {
	private static Map<String, String> xmlStr = new HashMap<String, String>(10);
	private Xml2StrReader(){}
	/**
	 * The default path is: classpath:webservice/
	 */
	private static String xmlStr(String fileName) throws Exception{
		SAXReader reader = new SAXReader();//Get the parser of dom4j
		Resource res = new ClassPathResource("webservice/"+fileName);
		Document document = reader.read(res.getInputStream());
		String text = document.asXML();
		return text;
	}
	
	/**
	 * Take advantage of the feature that HashMap.put calls the get method if it exists
	 * Guarantee that no error is thrown when storing to memory. When it is a big deal, when concurrency occurs, it will be parsed once more, regardless of concurrency.
	 */
	public static String getXmlStrFactory(String fileName) throws Exception{
		if(xmlStr.containsKey(fileName))
			return xmlStr.get(fileName);
		String str = xmlStr(fileName);
		xmlStr.put(fileName, str);
		return str;
	}
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327086231&siteId=291194637