2019-08-17java对象与json,xml互转

依赖的jar包,jackson-all-1.7.6.jar,xstream-1.4.4.jar
下载地址:
链接:https://pan.baidu.com/s/1LflD135qlQiIPGXw5XwDmw
提取码:6v29
复制这段内容后打开百度网盘手机App,操作更方便哦

package json_xml;


import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Date;

public class Test {
    public static void main(String[] args) throws IOException {
        Person person = new Person();
        person.setAdderess("hangzhou,China");
        person.setAge(18);
        person.setBirth(new Date());
        person.setName("zhangsan");

        //Json对象序列化
        String personJson =null;
        ObjectMapper mapper = new ObjectMapper();
        StringWriter sw = new StringWriter();
        JsonGenerator gen = new JsonFactory().createJsonGenerator(sw);
        mapper.writeValue(gen,person);
        gen.close();
        personJson = sw.toString();

        System.out.println(personJson);

        /**
         * {"name":"zhangsan","adderess":"hangzhou,China","age":18,"birth":1566030108817}
         */

        //Json对象反序列化
        Person zhangsan = mapper.readValue(personJson,Person.class);
        System.out.println(zhangsan.toString());
        /**
         * Person{adderess='hangzhou,China', age=18, birth=Sat Aug 17 16:21:48 CST 2019, name='zhangsan'}
         */


        //将Java对象序列化为XML格式
        XStream xStream = new XStream(new DomDriver());
        //设置person类的别名
        xStream.alias("person",Person.class);
        String personXML = xStream.toXML(person);
        System.out.println(personXML);
        /**
         * 
         *   hangzhou,China
         *   18
         *   2019-08-17 08:21:48.817 UTC
         *   zhangsan
         * 
         */


        //将XML反序列化还原为person对象
        Person zhangsan2 =(Person) xStream.fromXML(personXML);
        System.out.println(zhangsan2);
        /**
         * Person{adderess='hangzhou,China', age=18, birth=Sat Aug 17 16:21:48 CST 2019, name='zhangsan'}
         */
    }
}

你可能感兴趣的:(2019-08-17java对象与json,xml互转)