java 常用序列化和反序列化框架使用demo

package com.baidu.test;

import java.io.Serializable;
import java.util.List;

import org.msgpack.annotation.MessagePackMessage;

//Msgpack需要注释
@MessagePackMessage
public class Student implements Serializable{

	private static final long serialVersionUID = -2060550357305407661L;

	private Integer id;
	
	private String name;
	
	private String city;
	
	private List<Student> lovers;

	public Student(){}
	
	
	public Student(Integer id, String name, String city) {
		super();
		this.id = id;
		this.name = name;
		this.city = city;
	}
	
	
	

	public Student(Integer id, String name, String city, List<Student> lovers) {
		super();
		this.id = id;
		this.name = name;
		this.city = city;
		this.lovers = lovers;
	}


	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}


	public List<Student> getLovers() {
		return lovers;
	}


	public void setLovers(List<Student> lovers) {
		this.lovers = lovers;
	}

	@Override
	public String toString() {
		return "Student [city=" + city + ", id=" + id + ", lovers=" + lovers
				+ ", name=" + name + "]";
	}
	
}
package com.baidu.test.other;

import java.io.Serializable;
import java.util.List;

import org.msgpack.annotation.MessagePackMessage;

@MessagePackMessage
public class Teacher implements Serializable{

	private static final long serialVersionUID = -2060550357305407661L;

	private Integer id;
	
	private String name;
	
	private String city;
	
	private List<Teacher> lovers;

	public Teacher(){}
	
	
	public Teacher(Integer id, String name, String city) {
		super();
		this.id = id;
		this.name = name;
		this.city = city;
	}
	
	
	

	public Teacher(Integer id, String name, String city, List<Teacher> lovers) {
		super();
		this.id = id;
		this.name = name;
		this.city = city;
		this.lovers = lovers;
	}


	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}


	public List<Teacher> getLovers() {
		return lovers;
	}


	public void setLovers(List<Teacher> lovers) {
		this.lovers = lovers;
	}


	@Override
	public String toString() {
		return "Teacher [city=" + city + ", id=" + id + ", lovers=" + lovers
				+ ", name=" + name + "]";
	}



	
	
	
	
	
	
}
package com.baidu.test;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baidu.test.other.Teacher;

/*


 一个JSON库涉及的最基本功能就是序列化和反序列化。Fastjson支持java bean的直接序列化。
 使用com.alibaba.fastjson.JSON这个类进行序列化和反序列化。

 http://blog.csdn.net/yuanjian19900610/article/details/37737087
 */

public class TestFastJson {

	@SuppressWarnings("unchecked")
	public static void test002() {

		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("username", "zhangsan");
		map.put("age", 24);
		map.put("sex", "男");

		// map集合
		HashMap<String, Object> temp = new HashMap<String, Object>();
		temp.put("name", "xiaohong");
		temp.put("age", "23");
		map.put("girlInfo", temp);

		// list集合
		List<String> list = new ArrayList<String>();
		list.add("爬山");
		list.add("骑车");
		list.add("旅游");
		map.put("hobby", list);

		/*
		 * JSON 序列化,默认序列化出的JSON字符串中键值对是使用双引号,如果需要单引号的JSON字符串, [eg:String
		 * jsonString =
		 * JSON.toJSONString(map,SerializerFeature.UseSingleQuotes);]
		 * fastjson序列化时可以选择的SerializerFeature有十几个属性,你可以按照自己的需要去选择使用。
		 */
		String jsonString = JSON.toJSONString(map);
		System.out.println("JSON=" + jsonString);

		// 反序列化
		HashMap<String, Object> map_unserial = JSON.parseObject(jsonString,
				HashMap.class);

		System.out.println(map_unserial);

	}

	public static void main(String[] args) {

		test001();
		 test002();
		test003();
		test004();

	}

	// 日期格式化
	public static void test003() {

		Date date = new Date();
		// 输出毫秒值
		System.out.println(JSON.toJSONString(date));
		// 默认格式为yyyy-MM-dd HH:mm:ss
		System.out.println(JSON.toJSONString(date,
				SerializerFeature.WriteDateUseDateFormat));
		// 根据自定义格式输出日期
		System.out.println(JSON.toJSONStringWithDateFormat(date, "yyyy-MM-dd",
				SerializerFeature.WriteDateUseDateFormat));

	}

	/** 泛型的反序列化 */
	public static void test004() {
		String json = "{\"user\":{\"city\":\"来自北京\",\"name\":\"zhangsan\",\"id\":25}}";
		Map<String, Student> map = JSON.parseObject(json,
				new TypeReference<Map<String, Student>>() {
				});
		System.out.println(map.get("user"));

	}

	private static void test001() {
		Student studentLover = new Student(11, "name_wjh", "beijing");

		List<Student> lovers = new ArrayList<Student>();
		lovers.add(studentLover);
		lovers.add(new Student(12, "name_wjh", "北京"));
		lovers.add(new Student(13, "name_wjh", "上海"));

		Student student = new Student(1, "name_xx", "南宁", lovers);
		// System.out.println(JSON.toJSONString(student,
		// SerializerFeature.QuoteFieldNames));
		// 序列化
		String result = JSON.toJSONString(student);
		System.out.println(result);
		// 反序列化
		Student student2 = JSON.parseObject(result, Student.class);
		System.out.println(student2);

		// fastjson 强大,可以直接反序列化为其他类,只要属性名对应
		Teacher teacher = JSON.parseObject(result, Teacher.class);

		System.out.println(teacher);
	}

}
package com.baidu.test;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.util.Base64;

import com.baidu.test.other.Teacher;
import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;

/*

 注意:

 1. 在Hessian远程调用方法中,客户端中的接口类必须和服务器中的接口类一样,方法名称也一样

 2. 在接口类中,不要写重构的方法,Hessian不能识别重构的方法。

 3. 方法参数中,如果有自定义实体对象entity,则有以下几注意点:

 a  entity的package名必须同服务器上的package,否则会在服务端上报找不到此类

 b  entity必须是可序列化的,如果是组合对象,则可序列化应该可递归下去,除非不需要组合

 4. 方法返回值中,如果有自定义对象,同2,如果是集合对象,则为List(lists and arrays) & map(maps and dictionaries)

 5. Hessian 不支持文件传输,如需要文件传输,则传递数据流实现(下一文档说明)


 */
public class TestHessian {

	public static byte[] serialize(Object obj) throws IOException {
		if (obj == null)
			throw new NullPointerException();

		ByteArrayOutputStream os = new ByteArrayOutputStream();
		HessianOutput ho = new HessianOutput(os);
		ho.writeObject(obj);
		return os.toByteArray();
	}

	public static Object deserialize(byte[] by) throws IOException {
		if (by == null)
			throw new NullPointerException();

		ByteArrayInputStream is = new ByteArrayInputStream(by);
		HessianInput hi = new HessianInput(is);
		return hi.readObject();
	}

	public static void main(String[] args) throws Exception {

		List<Student> students = new ArrayList<Student>();
		students.add(new Student(11, "name_wjh", "北京11"));
		students.add(new Student(12, "name_wjh", "北京"));
		students.add(new Student(13, "name_wjh", "上海"));
		Student myStudent = new Student(10, "xx", "xxx", students);
		System.out.println(myStudent);
		byte[] buffer = serialize(myStudent);
		String str = Base64.encodeToString(buffer, Base64.DEFAULT);
		System.out.println(str);
		Student student = (Student) deserialize(Base64.decode(str,
				Base64.DEFAULT));
		System.out.println(student);

		// 不能转换为其他类
		Teacher teacher = (Teacher) deserialize(Base64.decode(str,
				Base64.DEFAULT));
		System.out.println(teacher);

	}
}


 

package com.baidu.test;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.map.ObjectMapper;

import com.baidu.test.other.Teacher;

//http://blog.csdn.net/subuser/article/details/19127003
public class TestJackson {

	public static void main(String[] args) throws Exception {

		List<Student> students = new ArrayList<Student>();

		students.add(new Student(11, "name_wjh", "北京11"));
		students.add(new Student(12, "name_wjh", "北京"));
		students.add(new Student(13, "name_wjh", "上海"));

		Student myStudent = new Student(10, "xx", "xxx", students);

		ObjectMapper mapper = new ObjectMapper();

		// convert user object to json string, and save to a file
		mapper.writeValue(new File("user.json"), myStudent);

	
		// read from file, convert it to user class
		Student student = mapper
				.readValue(new File("user.json"), Student.class);
		System.out.println(student);

		Teacher teacher = mapper
				.readValue(new File("user.json"), Teacher.class);
		System.out.println(teacher);
		
		//
		String data=mapper.writeValueAsString(myStudent);
		System.out.println(data);
		Student student2=mapper.readValue(data.getBytes(), Student.class);
		System.out.println(student2);
		
		Teacher teacher2=mapper.readValue(data.getBytes(), Teacher.class);
		System.out.println(teacher2);


	}
}
package com.baidu.test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baidu.test.other.Teacher;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

// http://json-lib.sourceforge.net/
public class testJsonlib {

	public static void main(String[] args) {
		

		List<Student> students = new ArrayList<Student>();
		students.add(new Student(11, "name_wjh", "北京11"));
		students.add(new Student(12, "name_wjh", "北京"));
		students.add(new Student(13, "name_wjh", "上海"));
		Student myStudent = new Student(10, "xx", "xxx", students);
		
		JSONObject js = JSONObject.fromObject(myStudent);  
		String str=js.toString();
        System.out.println(str);  
        
        JSONObject jsonObject = JSONObject.fromObject(str);  
        
        /*
        JsonConfig jsonConfig = new JsonConfig();  
  
        jsonConfig.setRootClass(Student.class);  
        Map<String, Class> classMap = new HashMap<String, Class>();  
        classMap.put("lovers", Student.class); // 指定JsonRpcRequest的request字段的内部类型  
        jsonConfig.setClassMap(classMap);  
          */
        Student student = (Student) JSONObject.toBean(jsonObject, Student.class);         
        System.out.println(student); 
        //不好用
        Teacher teacher = (Teacher) JSONObject.toBean(jsonObject, Teacher.class);         
        System.out.println(teacher); 
        
        
	}
}
package com.baidu.test;


import java.util.ArrayList;
import java.util.List;

import android.util.Base64;

import com.baidu.test.other.Teacher;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Registration;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;

public class TestKryo {

	private static void test001() {
		
		Kryo kryo = new Kryo();
		// kryo.setReferences(true);
		// kryo.setRegistrationRequired(true);
		// kryo.setInstantiatorStrategy(new StdInstantiatorStrategy());
		// 注册类
		Registration registration = kryo.register(Student.class);
		long time = System.currentTimeMillis();
		for (int i = 0; i < 2; i++) {
			// 序列化
			Output output = null;
			// ByteArrayOutputStream outStream = new ByteArrayOutputStream();
			// output = new Output( outStream , 4096);
			output = new Output(1, 4096);
			List<Student> students = new ArrayList<Student>();

			students.add(new Student(11, "name_wjh", "北京11"));
			students.add(new Student(12, "name_wjh", "北京"));
			students.add(new Student(13, "name_wjh", "上海"));

			Student myStudent = new Student(10, "xx", "xxx", students);

			kryo.writeObject(output, myStudent);
			byte[] bb = output.toBytes();
			output.flush();

			String str=Base64.encodeToString(bb, Base64.DEFAULT);
			System.out.println(str);
			
			// 反序列化
			Input input = new Input(Base64.decode(str, Base64.DEFAULT));
			Student s = (Student) kryo.readObject(input, registration.getType());
			System.out.println(s);
			input.close();
			// 反序列化为其他类
			input = new Input(Base64.decode(str, Base64.DEFAULT));
			Teacher teacher = (Teacher) kryo.readObject(input, Teacher.class);
			System.out.println(teacher);
			input.close();
		}
		time = System.currentTimeMillis() - time;
		System.out.println("time:" + time);
	}

	public static void main(String[] args) throws Exception {

		test001();
	}

}
package com.baidu.test;


import java.util.ArrayList;
import java.util.List;

import org.msgpack.MessagePack;

import com.baidu.test.other.Teacher;

import android.util.Base64;

public class TestMsgpack {

	public static void main(String[] args) throws Exception {

		List<Student> students = new ArrayList<Student>();

		students.add(new Student(11, "name_wjh", "北京11"));
		students.add(new Student(12, "name_wjh", "北京"));
		students.add(new Student(13, "name_wjh", "上海"));

		Student myStudent = new Student(10, "xx", "xxx", students);

		// Serialize
		byte[] raw = MessagePack.pack(myStudent);

		String str = Base64.encodeToString(raw, Base64.DEFAULT);
		System.out.println(str);

		// Deserialize
		Student student = MessagePack.unpack(
				Base64.decode(str, Base64.DEFAULT), Student.class);
		System.out.println(student);
		
		// Deserialize other class
		Teacher teacher = MessagePack.unpack(
				Base64.decode(str, Base64.DEFAULT), Teacher.class);
		System.out.println(teacher);
		
		
	}

}
package com.baidu.test;

import java.util.ArrayList;
import java.util.List;

import org.msgpack.MessagePack;

import android.util.Base64;

import com.github.xsonorg.XSON;

public class TestXson {
	
	public static void main(String[] args) {
		
		List<Student> students = new ArrayList<Student>();

		students.add(new Student(11, "name_wjh", "北京11"));
		students.add(new Student(12, "name_wjh", "北京"));
		students.add(new Student(13, "name_wjh", "上海"));

		Student myStudent = new Student(10, "xx", "xxx", students);
		byte[] buffer=XSON.write(myStudent);
		//失败
		String str = Base64.encodeToString(buffer, Base64.DEFAULT);
		System.out.println(str);

		Student student=XSON.parse(Base64.decode(str, Base64.DEFAULT));
		System.out.println(student);
		
		
		
	}

}


源码下载:http://download.csdn.net/detail/earbao/8906249






 

你可能感兴趣的:(java 常用序列化和反序列化框架使用demo)