xstream学习,对象和xml之间转换,对象和json之间转换

前端之家收集整理的这篇文章主要介绍了xstream学习,对象和xml之间转换,对象和json之间转换前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1、测试对象

package domain;

import java.util.Date;

public class User {
	private String name;
	private int age;
	private Date birthday;
	private Car car;
	private List<Book> books;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public Car getCar() {
		return car;
	}
	public void setCar(Car car) {
		this.car = car;
	}
	public List<Book> getBooks() {
		return books;
	}
	public void setBooks(List<Book> books) {
		this.books = books;
	}
	@Override
	public String toString() {
		return "User [name=" + name + ",age=" + age + ",birthday=" + birthday
				+ ",car=" + "Car [brand=" + car.getBrand() + ",price=" + car.getPrice() + ",factory="
				+ car.getFactory() + "]" + ",books=" + books + "]";
	}

	
}

package domain;

public class Book {

	private String bookName;
	private double price;
	private String author;
	public String getBookName() {
		return bookName;
	}
	public void setBookName(String bookName) {
		this.bookName = bookName;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	@Override
	public String toString() {
		return "Book [bookName=" + bookName + ",price=" + price + ",author="
				+ author + "]";
	}
	
	
}

package domain;

public class Car {

	
	private String brand;
	private double price;
	private String factory;
	public String getBrand() {
		return brand;
	}
	public void setBrand(String brand) {
		this.brand = brand;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	public String getFactory() {
		return factory;
	}
	public void setFactory(String factory) {
		this.factory = factory;
	}
	@Override
	public String toString() {
		return "Car [brand=" + brand + ",factory="
				+ factory + "]";
	}
	
	
}

2、对象到xml的转换
package test;

import java.util.ArrayList;

public class TestBean2XML {

	//XStream 同时可以转换list和map
	public static void main(String[] args) {
//		map2XML();
		//------Car对象-----//
		Car car = new Car();
		car.setBrand("宝马");
		car.setFactory("上汽");
		car.setPrice(500000);
		//------Car对象-----//
		
		//------Book对象-----//
		Book book1 = new Book();
		book1.setBookName("语文");
		book1.setAuthor("张三");
		book1.setPrice(40.6);
		Book book2 = new Book();
		book2.setBookName("数学");
		book2.setAuthor("李四");
		book2.setPrice(23.5);
		Book book3 = new Book();
		book3.setBookName("英语");
		book3.setAuthor("王五");
		book3.setPrice(34);
		//------Book对象-----//
		
		//------User对象-----//
		User user = new User();
		user.setName("小红");
		user.setAge(12);
		user.setBirthday(new Date());
		user.setCar(car);
		List<Book> list = new ArrayList<Book>();
		list.add(book1);
		list.add(book2);
		list.add(book3);
		user.setBooks(list);
		//------User对象-----//
		
		//测试根据bean生成xml
		XStream xStream = new XStream();
//		xStream.alias("user",User.class);
		//将类重命名
		xStream.aliasType("用户",User.class);
		xStream.alias("book",Book.class);
		xStream.alias("car",Car.class);
		/*
		*/
		
		//测试重命名属性
		/*
		xStream.aliasField("姓名",User.class,"name");
		xStream.aliasField("汽车价格",Car.class,"price");
		xStream.aliasField("作者",Book.class,"author");
		*/
		
		//测试将字段申明在 xml的属性节点上,而非文本节点上,并重命名
		xStream.aliasAttribute(User.class,"name","姓名");
		xStream.aliasAttribute(Car.class,"price","汽车价格");
		xStream.aliasAttribute(Book.class,"author","作者");
		String xml = xStream.toXML(user);
//		System.out.println(xml);
	}
	
	
	//将map转换为xml
	public static void map2XML(){
		 	Map<String,Book> map = new HashMap<String,Book>();
		 	Book bean1 = new Book();
		 	bean1.setBookName("语文");
		 	bean1.setPrice(234);
		 	bean1.setAuthor("张三");
		 	Book bean2 = new Book();
		 	bean2.setBookName("语文");
		 	bean2.setPrice(123);
		 	bean2.setAuthor("李四");
		 	
	        map.put("No.1",bean1);//put
	        map.put("No.3",bean2);//put
	        XStream xStream = new XStream();
	        xStream.alias("book",Book.class);
	        xStream.alias("key",String.class);
	        xStream.useAttributeFor(Book.class,"bookName");
			String xml = xStream.toXML(map);
	        System.out.println(xml);
	}
}

3、xml到对象的转换
package test;

import java.text.ParseException;

public class TestXML2Bean {

	static String xml = "<user name = \"小红\">"+
			  "<age>12</age>"+
			  "<birthday>2015-07-14 14:33:42.567 UTC</birthday>"+
			  "<car>"+
			    "<brand>宝马</brand>"+
			    "<price>500000.0</price>"+
			    "<factory>上汽</factory>"+
			  "</car>"+
			  "<books>"+
			    "<book>"+
			      "<bookName>语文</bookName>"+
			      "<price>40.6</price>"+
			      "<author>张三</author>"+
			    "</book>"+
			    "<book>"+
			      "<bookName>数学</bookName>"+
			      "<price>23.5</price>"+
			      "<author>李四</author>"+
			    "</book>"+
			    "<book>"+
			      "<bookName>英语</bookName>"+
			      "<price>34.0</price>"+
			      "<author>王五</author>"+
			    "</book>"+
			  "</books>"+
			"</user>";
	public static void main(String[] args) {
		//这里一定要是用 DomDriver才能fromXML
		XStream xStream = new XStream(new DomDriver());
		xStream.alias("user",Car.class);
		
		xStream.registerConverter( new DateConverter());
		//如果是属性节点要同步设置xStream
		xStream.aliasAttribute(User.class,"name");
		User user = (User)xStream.fromXML(xml);
		System.out.println(user.toString());
	}
}
 class DateConverter  implements Converter {  
	 @Override  
	 public boolean canConvert(Class arg0) {  
	  
	  return Date.class == arg0;  
	 }  
	 @Override  
	 public void marshal(Object arg0,HierarchicalStreamWriter arg1,MarshallingContext arg2) {  
	  
	    
	 }  
	 @Override  
	 public Object unmarshal(HierarchicalStreamReader reader,UnmarshallingContext arg1) {  
	        GregorianCalendar calendar = new GregorianCalendar();   
	        SimpleDateFormat dateFm = new SimpleDateFormat("yyyy-MM-dd"); //格式化当前系统日期  
	        try {  
	                calendar.setTime(dateFm.parse(reader.getValue()));  
	        } catch (ParseException e) {  
	                throw new ConversionException(e.getMessage(),e);  
	        }   
	        return calendar.getTime();  
	  
	 }  
 }

4、对象到json的转换
package test;

import java.io.Writer;

public class TestBean2JSON {

	public static void main(String[] args) {
		Car car = new Car();
		car.setBrand("宝马");
		car.setFactory("上汽");
		car.setPrice(500000);
		// ------Car对象-----//

		// ------Book对象-----//
		Book book1 = new Book();
		book1.setBookName("语文");
		book1.setAuthor("张三");
		book1.setPrice(40.6);
		Book book2 = new Book();
		book2.setBookName("数学");
		book2.setAuthor("李四");
		book2.setPrice(23.5);
		Book book3 = new Book();
		book3.setBookName("英语");
		book3.setAuthor("王五");
		book3.setPrice(34);
		// ------Book对象-----//

		// ------User对象-----//
		User user = new User();
		user.setName("小红");
		user.setAge(12);
		user.setBirthday(new Date());
		user.setCar(car);
		List<Book> list = new ArrayList<Book>();
		list.add(book1);
		list.add(book2);
		list.add(book3);
		user.setBooks(list);
		
		//使用JettisonMappedXmlDriver驱动转换
		 /*
		 XStream xstream = new XStream(new JettisonMappedXmlDriver());
		 xstream.setMode(XStream.NO_REFERENCES);
		 */
		
		//使用JsonHierarchicalStreamDriver驱动转换
		// 删除根节点
		
		XStream xstream = new XStream(new JsonHierarchicalStreamDriver() {
			public HierarchicalStreamWriter createWriter(Writer out) {
				return new JsonWriter(out,JsonWriter.DROP_ROOT_MODE);
			}
		});
		
		xstream.alias("user",User.class);
		xstream.alias("book",Book.class);
		xstream.alias("car",Car.class);
		String xml = xstream.toXML(user);
		System.out.println(xml);
	}
}

5、json到对象的转换
package test;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;

import domain.Book;
import domain.Car;
import domain.User;

public class TestJSON2Bean {

	static String json = "{\"user\": {"+
					  "\"name\": \"小红\","+
					  "\"age\": 12,"+
					  "\"birthday\": \"2015-07-15 13:51:18.907 UTC\","+
					  "\"car\": {"+
					    "\"brand\": \"宝马\","+
					    "\"price\": 500000.0,"+
					    "\"factory\": \"上汽\""+
					  "},"+
					  "\"books\": ["+
					    "{"+
					      "\"bookName\": \"语文\","+
					      "\"price\": 40.6,"+
					      "\"author\": \"张三\""+
					    "},"+
					    "{"+
					      "\"bookName\": \"数学\","+
					      "\"price\": 23.5,"+
					      "\"author\": \"李四\""+
					    "},"+
					    "{"+
					      "\"bookName\": \"英语\","+
					      "\"price\": 34.0,"+
					      "\"author\": \"王五\""+
					    "}"+
					  "]"+
					"}}";
	
	static String json1 = "{\"books\": ["+
		    "{"+
		      "\"bookName\": \"语文\","+
		      "\"price\": 40.6,"+
		      "\"author\": \"张三\""+
		    "},"+
		    "{"+
		      "\"bookName\": \"数学\","+
		      "\"price\": 23.5,"+
		      "\"author\": \"李四\""+
		    "},"+
		    "{"+
		      "\"bookName\": \"英语\","+
		      "\"price\": 34.0,"+
		      "\"author\": \"王五\""+
		    "}"+
		  "]}";
	public static void main(String[] args) {
		System.out.println(json);
		XStream xstream = new XStream(new JettisonMappedXmlDriver());
		xstream.alias("user",Book.class);
	    xstream.alias("car",Car.class);
	    User user = (User)xstream.fromXML(json);
	    //最后失败,貌似不能转 集合
		System.out.println(user.toString());
	}
}

猜你在找的XML相关文章