자바 상용 직렬 화 및 반 직렬 화 프레임 워 크 사용 demo

18517 단어
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

좋은 웹페이지 즐겨찾기