java 常用序列化和反序列化框架使用-json,kyro,jdk

不知道为什么博客不能收藏了,只好转载过来。

转载地址:http://blog.csdn.net/earbao/article/details/46914407


[java]  view plain  copy
  1. package com.baidu.test;  
  2.   
  3. import java.io.Serializable;  
  4. import java.util.List;  
  5.   
  6. import org.msgpack.annotation.MessagePackMessage;  
  7.   
  8. //Msgpack需要注释  
  9. @MessagePackMessage  
  10. public class Student implements Serializable{  
  11.   
  12.     private static final long serialVersionUID = -2060550357305407661L;  
  13.   
  14.     private Integer id;  
  15.       
  16.     private String name;  
  17.       
  18.     private String city;  
  19.       
  20.     private List<Student> lovers;  
  21.   
  22.     public Student(){}  
  23.       
  24.       
  25.     public Student(Integer id, String name, String city) {  
  26.         super();  
  27.         this.id = id;  
  28.         this.name = name;  
  29.         this.city = city;  
  30.     }  
  31.       
  32.       
  33.       
  34.   
  35.     public Student(Integer id, String name, String city, List<Student> lovers) {  
  36.         super();  
  37.         this.id = id;  
  38.         this.name = name;  
  39.         this.city = city;  
  40.         this.lovers = lovers;  
  41.     }  
  42.   
  43.   
  44.     public Integer getId() {  
  45.         return id;  
  46.     }  
  47.   
  48.     public void setId(Integer id) {  
  49.         this.id = id;  
  50.     }  
  51.   
  52.     public String getName() {  
  53.         return name;  
  54.     }  
  55.   
  56.     public void setName(String name) {  
  57.         this.name = name;  
  58.     }  
  59.   
  60.     public String getCity() {  
  61.         return city;  
  62.     }  
  63.   
  64.     public void setCity(String city) {  
  65.         this.city = city;  
  66.     }  
  67.   
  68.   
  69.     public List<Student> getLovers() {  
  70.         return lovers;  
  71.     }  
  72.   
  73.   
  74.     public void setLovers(List<Student> lovers) {  
  75.         this.lovers = lovers;  
  76.     }  
  77.   
  78.     @Override  
  79.     public String toString() {  
  80.         return "Student [city=" + city + ", id=" + id + ", lovers=" + lovers  
  81.                 + ", name=" + name + "]";  
  82.     }  
  83.       
  84. }  
[java]  view plain  copy
  1. package com.baidu.test.other;  
  2.   
  3. import java.io.Serializable;  
  4. import java.util.List;  
  5.   
  6. import org.msgpack.annotation.MessagePackMessage;  
  7.   
  8. @MessagePackMessage  
  9. public class Teacher implements Serializable{  
  10.   
  11.     private static final long serialVersionUID = -2060550357305407661L;  
  12.   
  13.     private Integer id;  
  14.       
  15.     private String name;  
  16.       
  17.     private String city;  
  18.       
  19.     private List<Teacher> lovers;  
  20.   
  21.     public Teacher(){}  
  22.       
  23.       
  24.     public Teacher(Integer id, String name, String city) {  
  25.         super();  
  26.         this.id = id;  
  27.         this.name = name;  
  28.         this.city = city;  
  29.     }  
  30.       
  31.       
  32.       
  33.   
  34.     public Teacher(Integer id, String name, String city, List<Teacher> lovers) {  
  35.         super();  
  36.         this.id = id;  
  37.         this.name = name;  
  38.         this.city = city;  
  39.         this.lovers = lovers;  
  40.     }  
  41.   
  42.   
  43.     public Integer getId() {  
  44.         return id;  
  45.     }  
  46.   
  47.     public void setId(Integer id) {  
  48.         this.id = id;  
  49.     }  
  50.   
  51.     public String getName() {  
  52.         return name;  
  53.     }  
  54.   
  55.     public void setName(String name) {  
  56.         this.name = name;  
  57.     }  
  58.   
  59.     public String getCity() {  
  60.         return city;  
  61.     }  
  62.   
  63.     public void setCity(String city) {  
  64.         this.city = city;  
  65.     }  
  66.   
  67.   
  68.     public List<Teacher> getLovers() {  
  69.         return lovers;  
  70.     }  
  71.   
  72.   
  73.     public void setLovers(List<Teacher> lovers) {  
  74.         this.lovers = lovers;  
  75.     }  
  76.   
  77.   
  78.     @Override  
  79.     public String toString() {  
  80.         return "Teacher [city=" + city + ", id=" + id + ", lovers=" + lovers  
  81.                 + ", name=" + name + "]";  
  82.     }  
  83.   
  84.   
  85.   
  86.       
  87.       
  88.       
  89.       
  90.       
  91.       
  92. }  
[java]  view plain  copy
  1. package com.baidu.test;  
  2. import java.util.ArrayList;  
  3. import java.util.Date;  
  4. import java.util.HashMap;  
  5. import java.util.List;  
  6. import java.util.Map;  
  7.   
  8. import com.alibaba.fastjson.JSON;  
  9. import com.alibaba.fastjson.TypeReference;  
  10. import com.alibaba.fastjson.serializer.SerializerFeature;  
  11. import com.baidu.test.other.Teacher;  
  12.   
  13. /* 
  14.  
  15.  
  16.  一个JSON库涉及的最基本功能就是序列化和反序列化。Fastjson支持java bean的直接序列化。 
  17.  使用com.alibaba.fastjson.JSON这个类进行序列化和反序列化。 
  18.  
  19.  http://blog.csdn.net/yuanjian19900610/article/details/37737087 
  20.  */  
  21.   
  22. public class TestFastJson {  
  23.   
  24.     @SuppressWarnings("unchecked")  
  25.     public static void test002() {  
  26.   
  27.         HashMap<String, Object> map = new HashMap<String, Object>();  
  28.         map.put("username""zhangsan");  
  29.         map.put("age"24);  
  30.         map.put("sex""男");  
  31.   
  32.         // map集合  
  33.         HashMap<String, Object> temp = new HashMap<String, Object>();  
  34.         temp.put("name""xiaohong");  
  35.         temp.put("age""23");  
  36.         map.put("girlInfo", temp);  
  37.   
  38.         // list集合  
  39.         List<String> list = new ArrayList<String>();  
  40.         list.add("爬山");  
  41.         list.add("骑车");  
  42.         list.add("旅游");  
  43.         map.put("hobby", list);  
  44.   
  45.         /* 
  46.          * JSON 序列化,默认序列化出的JSON字符串中键值对是使用双引号,如果需要单引号的JSON字符串, [eg:String 
  47.          * jsonString = 
  48.          * JSON.toJSONString(map,SerializerFeature.UseSingleQuotes);] 
  49.          * fastjson序列化时可以选择的SerializerFeature有十几个属性,你可以按照自己的需要去选择使用。 
  50.          */  
  51.         String jsonString = JSON.toJSONString(map);  
  52.         System.out.println("JSON=" + jsonString);  
  53.   
  54.         // 反序列化  
  55.         HashMap<String, Object> map_unserial = JSON.parseObject(jsonString,  
  56.                 HashMap.class);  
  57.   
  58.         System.out.println(map_unserial);  
  59.   
  60.     }  
  61.   
  62.     public static void main(String[] args) {  
  63.   
  64.         test001();  
  65.          test002();  
  66.         test003();  
  67.         test004();  
  68.   
  69.     }  
  70.   
  71.     // 日期格式化  
  72.     public static void test003() {  
  73.   
  74.         Date date = new Date();  
  75.         // 输出毫秒值  
  76.         System.out.println(JSON.toJSONString(date));  
  77.         // 默认格式为yyyy-MM-dd HH:mm:ss  
  78.         System.out.println(JSON.toJSONString(date,  
  79.                 SerializerFeature.WriteDateUseDateFormat));  
  80.         // 根据自定义格式输出日期  
  81.         System.out.println(JSON.toJSONStringWithDateFormat(date, "yyyy-MM-dd",  
  82.                 SerializerFeature.WriteDateUseDateFormat));  
  83.   
  84.     }  
  85.   
  86.     /** 泛型的反序列化 */  
  87.     public static void test004() {  
  88.         String json = "{\"user\":{\"city\":\"来自北京\",\"name\":\"zhangsan\",\"id\":25}}";  
  89.         Map<String, Student> map = JSON.parseObject(json,  
  90.                 new TypeReference<Map<String, Student>>() {  
  91.                 });  
  92.         System.out.println(map.get("user"));  
  93.   
  94.     }  
  95.   
  96.     private static void test001() {  
  97.         Student studentLover = new Student(11"name_wjh""beijing");  
  98.   
  99.         List<Student> lovers = new ArrayList<Student>();  
  100.         lovers.add(studentLover);  
  101.         lovers.add(new Student(12"name_wjh""北京"));  
  102.         lovers.add(new Student(13"name_wjh""上海"));  
  103.   
  104.         Student student = new Student(1"name_xx""南宁", lovers);  
  105.         // System.out.println(JSON.toJSONString(student,  
  106.         // SerializerFeature.QuoteFieldNames));  
  107.         // 序列化  
  108.         String result = JSON.toJSONString(student);  
  109.         System.out.println(result);  
  110.         // 反序列化  
  111.         Student student2 = JSON.parseObject(result, Student.class);  
  112.         System.out.println(student2);  
  113.   
  114.         // fastjson 强大,可以直接反序列化为其他类,只要属性名对应  
  115.         Teacher teacher = JSON.parseObject(result, Teacher.class);  
  116.   
  117.         System.out.println(teacher);  
  118.     }  
  119.   
  120. }  
[java]  view plain  copy
  1. package com.baidu.test;  
  2.   
  3. import java.io.ByteArrayInputStream;  
  4. import java.io.ByteArrayOutputStream;  
  5. import java.io.IOException;  
  6. import java.util.ArrayList;  
  7. import java.util.List;  
  8.   
  9. import android.util.Base64;  
  10.   
  11. import com.baidu.test.other.Teacher;  
  12. import com.caucho.hessian.io.HessianInput;  
  13. import com.caucho.hessian.io.HessianOutput;  
  14.   
  15. /* 
  16.  
  17.  注意: 
  18.  
  19.  1. 在Hessian远程调用方法中,客户端中的接口类必须和服务器中的接口类一样,方法名称也一样 
  20.  
  21.  2. 在接口类中,不要写重构的方法,Hessian不能识别重构的方法。 
  22.  
  23.  3. 方法参数中,如果有自定义实体对象entity,则有以下几注意点: 
  24.  
  25.  a  entity的package名必须同服务器上的package,否则会在服务端上报找不到此类 
  26.  
  27.  b  entity必须是可序列化的,如果是组合对象,则可序列化应该可递归下去,除非不需要组合 
  28.  
  29.  4. 方法返回值中,如果有自定义对象,同2,如果是集合对象,则为List(lists and arrays) & map(maps and dictionaries) 
  30.  
  31.  5. Hessian 不支持文件传输,如需要文件传输,则传递数据流实现(下一文档说明) 
  32.  
  33.  
  34.  */  
  35. public class TestHessian {  
  36.   
  37.     public static byte[] serialize(Object obj) throws IOException {  
  38.         if (obj == null)  
  39.             throw new NullPointerException();  
  40.   
  41.         ByteArrayOutputStream os = new ByteArrayOutputStream();  
  42.         HessianOutput ho = new HessianOutput(os);  
  43.         ho.writeObject(obj);  
  44.         return os.toByteArray();  
  45.     }  
  46.   
  47.     public static Object deserialize(byte[] by) throws IOException {  
  48.         if (by == null)  
  49.             throw new NullPointerException();  
  50.   
  51.         ByteArrayInputStream is = new ByteArrayInputStream(by);  
  52.         HessianInput hi = new HessianInput(is);  
  53.         return hi.readObject();  
  54.     }  
  55.   
  56.     public static void main(String[] args) throws Exception {  
  57.   
  58.         List<Student> students = new ArrayList<Student>();  
  59.         students.add(new Student(11"name_wjh""北京11"));  
  60.         students.add(new Student(12"name_wjh""北京"));  
  61.         students.add(new Student(13"name_wjh""上海"));  
  62.         Student myStudent = new Student(10"xx""xxx", students);  
  63.         System.out.println(myStudent);  
  64.         byte[] buffer = serialize(myStudent);  
  65.         String str = Base64.encodeToString(buffer, Base64.DEFAULT);  
  66.         System.out.println(str);  
  67.         Student student = (Student) deserialize(Base64.decode(str,  
  68.                 Base64.DEFAULT));  
  69.         System.out.println(student);  
  70.   
  71.         // 不能转换为其他类  
  72.         Teacher teacher = (Teacher) deserialize(Base64.decode(str,  
  73.                 Base64.DEFAULT));  
  74.         System.out.println(teacher);  
  75.   
  76.     }  
  77. }  


 

[java]  view plain  copy
  1. package com.baidu.test;  
  2.   
  3. import java.io.File;  
  4. import java.util.ArrayList;  
  5. import java.util.List;  
  6.   
  7. import org.codehaus.jackson.map.ObjectMapper;  
  8.   
  9. import com.baidu.test.other.Teacher;  
  10.   
  11. //http://blog.csdn.net/subuser/article/details/19127003  
  12. public class TestJackson {  
  13.   
  14.     public static void main(String[] args) throws Exception {  
  15.   
  16.         List<Student> students = new ArrayList<Student>();  
  17.   
  18.         students.add(new Student(11"name_wjh""北京11"));  
  19.         students.add(new Student(12"name_wjh""北京"));  
  20.         students.add(new Student(13"name_wjh""上海"));  
  21.   
  22.         Student myStudent = new Student(10"xx""xxx", students);  
  23.   
  24.         ObjectMapper mapper = new ObjectMapper();  
  25.   
  26.         // convert user object to json string, and save to a file  
  27.         mapper.writeValue(new File("user.json"), myStudent);  
  28.   
  29.       
  30.         // read from file, convert it to user class  
  31.         Student student = mapper  
  32.                 .readValue(new File("user.json"), Student.class);  
  33.         System.out.println(student);  
  34.   
  35.         Teacher teacher = mapper  
  36.                 .readValue(new File("user.json"), Teacher.class);  
  37.         System.out.println(teacher);  
  38.           
  39.         //  
  40.         String data=mapper.writeValueAsString(myStudent);  
  41.         System.out.println(data);  
  42.         Student student2=mapper.readValue(data.getBytes(), Student.class);  
  43.         System.out.println(student2);  
  44.           
  45.         Teacher teacher2=mapper.readValue(data.getBytes(), Teacher.class);  
  46.         System.out.println(teacher2);  
  47.   
  48.   
  49.     }  
  50. }  
[java]  view plain  copy
  1. package com.baidu.test;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.HashMap;  
  5. import java.util.List;  
  6. import java.util.Map;  
  7.   
  8. import com.baidu.test.other.Teacher;  
  9.   
  10. import net.sf.json.JSONObject;  
  11. import net.sf.json.JsonConfig;  
  12.   
  13. // http://json-lib.sourceforge.net/  
  14. public class testJsonlib {  
  15.   
  16.     public static void main(String[] args) {  
  17.           
  18.   
  19.         List<Student> students = new ArrayList<Student>();  
  20.         students.add(new Student(11"name_wjh""北京11"));  
  21.         students.add(new Student(12"name_wjh""北京"));  
  22.         students.add(new Student(13"name_wjh""上海"));  
  23.         Student myStudent = new Student(10"xx""xxx", students);  
  24.           
  25.         JSONObject js = JSONObject.fromObject(myStudent);    
  26.         String str=js.toString();  
  27.         System.out.println(str);    
  28.           
  29.         JSONObject jsonObject = JSONObject.fromObject(str);    
  30.           
  31.         /* 
  32.         JsonConfig jsonConfig = new JsonConfig();   
  33.    
  34.         jsonConfig.setRootClass(Student.class);   
  35.         Map<String, Class> classMap = new HashMap<String, Class>();   
  36.         classMap.put("lovers", Student.class); // 指定JsonRpcRequest的request字段的内部类型   
  37.         jsonConfig.setClassMap(classMap);   
  38.           */  
  39.         Student student = (Student) JSONObject.toBean(jsonObject, Student.class);           
  40.         System.out.println(student);   
  41.         //不好用  
  42.         Teacher teacher = (Teacher) JSONObject.toBean(jsonObject, Teacher.class);           
  43.         System.out.println(teacher);   
  44.           
  45.           
  46.     }  
  47. }  
[java]  view plain  copy
  1. package com.baidu.test;  
  2.   
  3.   
  4. import java.util.ArrayList;  
  5. import java.util.List;  
  6.   
  7. import android.util.Base64;  
  8.   
  9. import com.baidu.test.other.Teacher;  
  10. import com.esotericsoftware.kryo.Kryo;  
  11. import com.esotericsoftware.kryo.Registration;  
  12. import com.esotericsoftware.kryo.io.Input;  
  13. import com.esotericsoftware.kryo.io.Output;  
  14.   
  15. public class TestKryo {  
  16.   
  17.     private static void test001() {  
  18.           
  19.         Kryo kryo = new Kryo();  
  20.         // kryo.setReferences(true);  
  21.         // kryo.setRegistrationRequired(true);  
  22.         // kryo.setInstantiatorStrategy(new StdInstantiatorStrategy());  
  23.         // 注册类  
  24.         Registration registration = kryo.register(Student.class);  
  25.         long time = System.currentTimeMillis();  
  26.         for (int i = 0; i < 2; i++) {  
  27.             // 序列化  
  28.             Output output = null;  
  29.             // ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
  30.             // output = new Output( outStream , 4096);  
  31.             output = new Output(14096);  
  32.             List<Student> students = new ArrayList<Student>();  
  33.   
  34.             students.add(new Student(11"name_wjh""北京11"));  
  35.             students.add(new Student(12"name_wjh""北京"));  
  36.             students.add(new Student(13"name_wjh""上海"));  
  37.   
  38.             Student myStudent = new Student(10"xx""xxx", students);  
  39.   
  40.             kryo.writeObject(output, myStudent);  
  41.             byte[] bb = output.toBytes();  
  42.             output.flush();  
  43.   
  44.             String str=Base64.encodeToString(bb, Base64.DEFAULT);  
  45.             System.out.println(str);  
  46.               
  47.             // 反序列化  
  48.             Input input = new Input(Base64.decode(str, Base64.DEFAULT));  
  49.             Student s = (Student) kryo.readObject(input, registration.getType());  
  50.             System.out.println(s);  
  51.             input.close();  
  52.             // 反序列化为其他类  
  53.             input = new Input(Base64.decode(str, Base64.DEFAULT));  
  54.             Teacher teacher = (Teacher) kryo.readObject(input, Teacher.class);  
  55.             System.out.println(teacher);  
  56.             input.close();  
  57.         }  
  58.         time = System.currentTimeMillis() - time;  
  59.         System.out.println("time:" + time);  
  60.     }  
  61.   
  62.     public static void main(String[] args) throws Exception {  
  63.   
  64.         test001();  
  65.     }  
  66.   
  67. }  
[java]  view plain  copy
  1. package com.baidu.test;  
  2.   
  3.   
  4. import java.util.ArrayList;  
  5. import java.util.List;  
  6.   
  7. import org.msgpack.MessagePack;  
  8.   
  9. import com.baidu.test.other.Teacher;  
  10.   
  11. import android.util.Base64;  
  12.   
  13. public class TestMsgpack {  
  14.   
  15.     public static void main(String[] args) throws Exception {  
  16.   
  17.         List<Student> students = new ArrayList<Student>();  
  18.   
  19.         students.add(new Student(11"name_wjh""北京11"));  
  20.         students.add(new Student(12"name_wjh""北京"));  
  21.         students.add(new Student(13"name_wjh""上海"));  
  22.   
  23.         Student myStudent = new Student(10"xx""xxx", students);  
  24.   
  25.         // Serialize  
  26.         byte[] raw = MessagePack.pack(myStudent);  
  27.   
  28.         String str = Base64.encodeToString(raw, Base64.DEFAULT);  
  29.         System.out.println(str);  
  30.   
  31.         // Deserialize  
  32.         Student student = MessagePack.unpack(  
  33.                 Base64.decode(str, Base64.DEFAULT), Student.class);  
  34.         System.out.println(student);  
  35.           
  36.         // Deserialize other class  
  37.         Teacher teacher = MessagePack.unpack(  
  38.                 Base64.decode(str, Base64.DEFAULT), Teacher.class);  
  39.         System.out.println(teacher);  
  40.           
  41.           
  42.     }  
  43.   
  44. }  
[java]  view plain  copy
  1. package com.baidu.test;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. import org.msgpack.MessagePack;  
  7.   
  8. import android.util.Base64;  
  9.   
  10. import com.github.xsonorg.XSON;  
  11.   
  12. public class TestXson {  
  13.       
  14.     public static void main(String[] args) {  
  15.           
  16.         List<Student> students = new ArrayList<Student>();  
  17.   
  18.         students.add(new Student(11"name_wjh""北京11"));  
  19.         students.add(new Student(12"name_wjh""北京"));  
  20.         students.add(new Student(13"name_wjh""上海"));  
  21.   
  22.         Student myStudent = new Student(10"xx""xxx", students);  
  23.         byte[] buffer=XSON.write(myStudent);  
  24.         //失败  
  25.         String str = Base64.encodeToString(buffer, Base64.DEFAULT);  
  26.         System.out.println(str);  
  27.   
  28.         Student student=XSON.parse(Base64.decode(str, Base64.DEFAULT));  
  29.         System.out.println(student);  
  30.           
  31.           
  32.           
  33.     }  
  34.   
  35. }  


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


猜你喜欢

转载自blog.csdn.net/liang0000zai/article/details/51518296