package com.wa.spring.chapter14.demo;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver;
import com.wa.spring.chapter14.model.User;
/**
* 对象和json的相互转化
* @author Administrator
*
*/
public class SimpleJsonExample {
private static XStream xStream;
public static User getUser() throws ParseException{
User user = new User();
user.setId(12);
user.setUsername("东方不败");
user.setLastLoginDate(new Date());
user.setPassword("123456");
user.setRegisterDate(new SimpleDateFormat("yyyy-MM-dd").parse("2010-10-21"));
user.setLastLoginIp("192.189.0.102");
return user;
}
/**
* 连续的没有分隔符的json字符串
* @throws Exception
*
* 一长串字符串
* {"user":
* {
* "id":12,
* "username":"东方不败",
* "password":123456,
* "registerDate":"2010-10-20 16:00:00.0 UTC",
* "lastLoginDate":"2014-11-08 12:00:20.506 UTC",
* "lastLoginIp":"192.189.0.102"
* }
* }
*/
public static void ObjectToJSON() throws Exception{
User user = getUser();
FileOutputStream out = new FileOutputStream
(new File("D:\\workspace\\spring\\src\\com\\wa\\spring\\chapter14\\model\\user-json.json"));
xStream= new XStream(new JettisonMappedXmlDriver());
//为类设置别名
xStream.alias("user", User.class);
xStream.setMode(XStream.NO_REFERENCES);
xStream.toXML(user, out);
}
/**
* 直接生成格式良好的json字符串
* {"user": {
"id": 12,
"username": "东方不败",
"password": "123456",
"registerDate": "2010-10-20 16:00:00.0 UTC",
"lastLoginDate": "2014-11-08 12:05:08.15 UTC",
"lastLoginIp": "192.189.0.102"
}}
* @throws Exception
*/
public static void ObjectToGoodFormat() throws Exception{
User user = getUser();
FileOutputStream out = new FileOutputStream
(new File("D:\\workspace\\spring\\src\\com\\wa\\spring\\chapter14\\model\\user-format-json.json"));
/**
* Hierarchical
*
* 英 [haɪə'rɑːkɪk(ə)l] 美 [,haɪə'rɑrkɪkl] 全球发音 跟读 口语练习
adj. 分层的;等级体系的
*/
xStream= new XStream(new JsonHierarchicalStreamDriver());
//为类设置别名
xStream.alias("user", User.class);
xStream.setMode(XStream.NO_REFERENCES);
xStream.toXML(user, out);
}
public static void JSON2Object() throws Exception{
FileInputStream in= new FileInputStream
(new File("D:\\workspace\\spring\\src\\com\\wa\\spring\\chapter14\\model\\user-format-json.json"));
/**
* JsonHierarchicalStreamDriver不能将json转化为对象
* java.lang.UnsupportedOperationException:
* The JsonHierarchicalStreamDriver can only write JSON
*/
//xStream= new XStream(new JsonHierarchicalStreamDriver());
xStream= new XStream(new JettisonMappedXmlDriver());
xStream.alias("user", User.class);
User user = (User)xStream.fromXML(in);
System.out.println(user);
}
public static void main(String[] args) throws Exception{
//ObjectToJSON();
// ObjectToGoodFormat();
JSON2Object();
}
}