xStream完美转换XML、JSON

xStream框架

xStream可以轻易的将Java对象和xml文档相互转换,而且可以修改某个特定的属性和节点名称,而且也支持json的转换;

一、准备工作

1、 下载jar包、及官方资源

xStream的jar下载地址:

https://nexus.codehaus.org/content/repositories/releases/com/thoughtworks/xstream/xstream-distribution/1.3.1/xstream-distribution-1.3.1-bin.zip

官方的示例很全,官方参考示例:http://xstream.codehaus.org/tutorial.html

添加xstream-1.4.2.jar文件到工程中,就可以开始下面的工作;需要的jar如下:

xStream完美转换XML、JSON_第1张图片

2、 测试用例代码

     POJO-1

package com.upop.pojo;

public class PhoneNumber {
 private int code;
 private String number;
 
 public PhoneNumber(){
  
 }
 public PhoneNumber(int code, String number) {
  super();
  this.code = code;
  this.number = number;
 }

 public int getCode() {
  return code;
 }

 public void setCode(int code) {
  this.code = code;
 }

 public String getNumber() {
  return number;
 }

 public void setNumber(String number) {
  this.number = number;
 }

}

POJO-2

package com.upop.pojo;

public class Person {
 private String firstname;
 private String lastname;
 private PhoneNumber phone;
 private PhoneNumber fax;

 public Person(){
  
 }
 
 public Person(String firstname,String lastname){
  
 }
 public Person(String firstname, String lastname, PhoneNumber phone,
   PhoneNumber fax) {
  super();
  this.firstname = firstname;
  this.lastname = lastname;
  this.phone = phone;
  this.fax = fax;
 }

 public String getFirstname() {
  return firstname;
 }

 public void setFirstname(String firstname) {
  this.firstname = firstname;
 }

 public String getLastname() {
  return lastname;
 }

 public void setLastname(String lastname) {
  this.lastname = lastname;
 }

 public PhoneNumber getPhone() {
  return phone;
 }

 public void setPhone(PhoneNumber phone) {
  this.phone = phone;
 }

 public PhoneNumber getFax() {
  return fax;
 }

 public void setFax(PhoneNumber fax) {
  this.fax = fax;
 }

}
二、Java转换成XML或JSON

package com.upop.pojo;

import org.junit.Test;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;

public class XStreamTest {

 private XStream xstream = null;

 @Test
 public void testXml() {
  try {
   xstream = new XStream();
   xstream.alias("person", Person.class);
   //xstream.alias("phonenumber", PhoneNumber.class);
   Person joe = new Person("Joe", "Walnes");
   joe.setPhone(new PhoneNumber(123, "1234-456"));
   joe.setFax(new PhoneNumber(123, "9999-999"));
   System.out.println(xstream.toXML(joe));
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
 
 @Test
 public void testJson(){
   XStream xstream = new XStream(new JettisonMappedXmlDriver());
         xstream.setMode(XStream.NO_REFERENCES);
         xstream.alias("person", Person.class);
         Person joe = new Person("Joe", "Walnes");
   joe.setPhone(new PhoneNumber(123, "1234-456"));
   joe.setFax(new PhoneNumber(123, "9999-999"));
         System.out.println(xstream.toXML(joe));

 }

}

 

 

 

你可能感兴趣的:(xml,exception,json,String,jar,Class)