Json转换利器Gson

Json转换利器Gson之实例一-简单对象转化和带泛型的List转化

Gson 是 Google 提供的用来在 Java 对象和 JSON 数据之间进行映射的 Java 类库。可以将一个 JSON 字符串转成一个 Java 对象,或者反过来。

jar和源码下载地址: http://code.google.com/p/google-gson/downloads/list


实体类:

[java]  view plain copy
  1.   
[java]  view plain copy
  1. public class Student {  
  2.     private int id;  
  3.     private String name;  
  4.     private Date birthDay;  
  5.   
  6.     public int getId() {  
  7.         return id;  
  8.     }  
  9.   
  10.     public void setId(int id) {  
  11.         this.id = id;  
  12.     }  
  13.   
  14.     public String getName() {  
  15.         return name;  
  16.     }  
  17.   
  18.     public void setName(String name) {  
  19.         this.name = name;  
  20.     }  
  21.   
  22.     public Date getBirthDay() {  
  23.         return birthDay;  
  24.     }  
  25.   
  26.     public void setBirthDay(Date birthDay) {  
  27.         this.birthDay = birthDay;  
  28.     }  
  29.   
  30.     @Override  
  31.     public String toString() {  
  32.         return "Student [birthDay=" + birthDay + ", id=" + id + ", name="  
  33.                 + name + "]";  
  34.     }  
  35.   
  36. }  

测试类:

[html]  view plain copy
  1. import java.util.ArrayList;  
  2. import java.util.Date;  
  3. import java.util.List;  
  4.   
  5. import com.google.gson.Gson;  
  6. import com.google.gson.reflect.TypeToken;  
  7.   
  8. public class GsonTest1 {  
  9.   
  10.     public static void main(String[] args) {  
  11.         Gson gson = new Gson();  
  12.   
  13.         Student student1 = new Student();  
  14.         student1.setId(1);  
  15.         student1.setName("李坤");  
  16.         student1.setBirthDay(new Date());  
  17.   
  18.         // //  
  19.         System.out.println("----------简单对象之间的转化-------------");  
  20.         // 简单的bean转为json  
  21.         String s1 = gson.toJson(student1);  
  22.         System.out.println("简单Bean转化为Json===" + s1);  
  23.   
  24.         // json转为简单Bean  
  25.         Student student = gson.fromJson(s1, Student.class);  
  26.         System.out.println("Json转为简单Bean===" + student);  
  27.         // 结果:  
  28.         // 简单Bean转化为Json==={"id":1,"name":"李坤","birthDay":"Jun 22, 2012 8:27:52 AM"}  
  29.         // Json转为简单Bean===Student [birthDay=Fri Jun 22 08:27:52 CST 2012, id=1,  
  30.         // name=李坤]  
  31.         // //  
  32.   
  33.         Student student2 = new Student();  
  34.         student2.setId(2);  
  35.         student2.setName("曹贵生");  
  36.         student2.setBirthDay(new Date());  
  37.   
  38.         Student student3 = new Student();  
  39.         student3.setId(3);  
  40.         student3.setName("柳波");  
  41.         student3.setBirthDay(new Date());  
  42.   
  43.         List<Student> list = new ArrayList<Student>();  
  44.         list.add(student1);  
  45.         list.add(student2);  
  46.         list.add(student3);  
  47.   
  48.         System.out.println("----------带泛型的List之间的转化-------------");  
  49.         // 带泛型的list转化为json  
  50.         String s2 = gson.toJson(list);  
  51.         System.out.println("带泛型的list转化为json==" + s2);  
  52.   
  53.         // json转为带泛型的list  
  54.         List<Student> retList = gson.fromJson(s2,  
  55.                 new TypeToken<List<Student>>() {  
  56.                 }.getType());  
  57.         for (Student stu : retList) {  
  58.             System.out.println(stu);  
  59.         }  
  60.   
  61.         // 结果:  
  62.         // 带泛型的list转化为json==[{"id":1,"name":"李坤","birthDay":"Jun 22, 2012 8:28:52 AM"},{"id":2,"name":"曹贵生","birthDay":"Jun 22, 2012 8:28:52 AM"},{"id":3,"name":"柳波","birthDay":"Jun 22, 2012 8:28:52 AM"}]  
  63.         // Student [birthDay=Fri Jun 22 08:28:52 CST 2012, id=1name=李坤]  
  64.         // Student [birthDay=Fri Jun 22 08:28:52 CST 2012, id=2name=曹贵生]  
  65.         // Student [birthDay=Fri Jun 22 08:28:52 CST 2012, id=3name=柳波]  
  66.   
  67.     }  
  68. }  

执行结果:

[plain]  view plain copy
  1. ----------简单对象之间的转化-------------  
  2. 简单Bean转化为Json==={"id":1,"name":"李坤","birthDay":"Jun 22, 2012 9:10:31 PM"}  
  3. Json转为简单Bean===Student [birthDay=Fri Jun 22 21:10:31 CST 2012, id=1, name=李坤]  
  4. ----------带泛型的List之间的转化-------------  
  5. 带泛型的list转化为json==[{"id":1,"name":"李坤","birthDay":"Jun 22, 2012 9:10:31 PM"},{"id":2,"name":"曹贵生","birthDay":"Jun 22, 2012 9:10:31 PM"},{"id":3,"name":"柳波","birthDay":"Jun 22, 2012 9:10:31 PM"}]  
  6. Student [birthDay=Fri Jun 22 21:10:31 CST 2012, id=1, name=李坤]  
  7. Student [birthDay=Fri Jun 22 21:10:31 CST 2012, id=2, name=曹贵生]  
  8. Student [birthDay=Fri Jun 22 21:10:31 CST 2012, id=3, name=柳波]  

Json转换利器Gson之实例一-简单对象转化和带泛型的List转化 (http://blog.csdn.net/lk_blog/article/details/7685169)
Json转换利器Gson之实例二-Gson注解和GsonBuilder (http://blog.csdn.net/lk_blog/article/details/7685190)
Json转换利器Gson之实例三-Map处理(上) (http://blog.csdn.net/lk_blog/article/details/7685210)
Json转换利器Gson之实例四-Map处理(下) (http://blog.csdn.net/lk_blog/article/details/7685224)
Json转换利器Gson之实例五-实际开发中的特殊需求处理 (http://blog.csdn.net/lk_blog/article/details/7685237)
Json转换利器Gson之实例六-注册TypeAdapter及处理Enum类型 (http://blog.csdn.net/lk_blog/article/details/7685347)


实例代码下载: http://download.csdn.net/detail/lk_blog/4387822


Json转换利器Gson之实例二-Gson注解和GsonBuilder

有时候我们不需要把实体的所有属性都导出,只想把一部分属性导出为Json.

有时候我们的实体类会随着版本的升级而修改.

有时候我们想对输出的json默认排好格式.

... ...

请看下面的例子吧:

实体类:

[java]  view plain copy
  1. import java.util.Date;  
  2.   
  3. import com.google.gson.annotations.Expose;  
  4. import com.google.gson.annotations.SerializedName;  
  5.   
  6. public class Student {  
  7.     private int id;  
  8.       
  9.     @Expose  
  10.     private String name;  
  11.       
  12.     @Expose  
  13.     @SerializedName("bir")  
  14.     private Date birthDay;  
  15.   
  16.     public int getId() {  
  17.         return id;  
  18.     }  
  19.   
  20.     public void setId(int id) {  
  21.         this.id = id;  
  22.     }  
  23.   
  24.     public String getName() {  
  25.         return name;  
  26.     }  
  27.   
  28.     public void setName(String name) {  
  29.         this.name = name;  
  30.     }  
  31.   
  32.     public Date getBirthDay() {  
  33.         return birthDay;  
  34.     }  
  35.   
  36.     public void setBirthDay(Date birthDay) {  
  37.         this.birthDay = birthDay;  
  38.     }  
  39.   
  40.     @Override  
  41.     public String toString() {  
  42.         return "Student [birthDay=" + birthDay + ", id=" + id + ", name="  
  43.                 + name + "]";  
  44.     }  
  45.   
  46. }  

测试类:

[java]  view plain copy
  1. import java.util.ArrayList;  
  2. import java.util.Date;  
  3. import java.util.List;  
  4.   
  5. import com.google.gson.FieldNamingPolicy;  
  6. import com.google.gson.Gson;  
  7. import com.google.gson.GsonBuilder;  
  8. import com.google.gson.reflect.TypeToken;  
  9.   
  10. public class GsonTest2 {  
  11.   
  12.     public static void main(String[] args) {  
  13.         //注意这里的Gson的构建方式为GsonBuilder,区别于test1中的Gson gson = new Gson();  
  14.         Gson gson = new GsonBuilder()  
  15.         .excludeFieldsWithoutExposeAnnotation() //不导出实体中没有用@Expose注解的属性  
  16.         .enableComplexMapKeySerialization() //支持Map的key为复杂对象的形式  
  17.         .serializeNulls().setDateFormat("yyyy-MM-dd HH:mm:ss:SSS")//时间转化为特定格式    
  18.         .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)//会把字段首字母大写,注:对于实体上使用了@SerializedName注解的不会生效.  
  19.         .setPrettyPrinting() //对json结果格式化.  
  20.         .setVersion(1.0)    //有的字段不是一开始就有的,会随着版本的升级添加进来,那么在进行序列化和返序列化的时候就会根据版本号来选择是否要序列化.  
  21.                             //@Since(版本号)能完美地实现这个功能.还的字段可能,随着版本的升级而删除,那么  
  22.                             //@Until(版本号)也能实现这个功能,GsonBuilder.setVersion(double)方法需要调用.  
  23.         .create();  
  24.           
  25.           
  26.   
  27.         Student student1 = new Student();  
  28.         student1.setId(1);  
  29.         student1.setName("李坤");  
  30.         student1.setBirthDay(new Date());  
  31.   
  32.         // //  
  33.         System.out.println("----------简单对象之间的转化-------------");  
  34.         // 简单的bean转为json  
  35.         String s1 = gson.toJson(student1);  
  36.         System.out.println("简单Bean转化为Json===" + s1);  
  37.   
  38.         // json转为简单Bean  
  39.         Student student = gson.fromJson(s1, Student.class);  
  40.         System.out.println("Json转为简单Bean===" + student);  
  41.         // //  
  42.   
  43.         Student student2 = new Student();  
  44.         student2.setId(2);  
  45.         student2.setName("曹贵生");  
  46.         student2.setBirthDay(new Date());  
  47.   
  48.         Student student3 = new Student();  
  49.         student3.setId(3);  
  50.         student3.setName("柳波");  
  51.         student3.setBirthDay(new Date());  
  52.   
  53.         List<Student> list = new ArrayList<Student>();  
  54.         list.add(student1);  
  55.         list.add(student2);  
  56.         list.add(student3);  
  57.   
  58.         System.out.println("----------带泛型的List之间的转化-------------");  
  59.         // 带泛型的list转化为json  
  60.         String s2 = gson.toJson(list);  
  61.         System.out.println("带泛型的list转化为json==" + s2);  
  62.   
  63.         // json转为带泛型的list  
  64.         List<Student> retList = gson.fromJson(s2,  
  65.                 new TypeToken<List<Student>>() {  
  66.                 }.getType());  
  67.         for (Student stu : retList) {  
  68.             System.out.println(stu);  
  69.         }  
  70.           
  71.     }  
  72. }  

输出结果:

[plain]  view plain copy
  1. ----------简单对象之间的转化-------------  
  2. 简单Bean转化为Json==={  
  3.   "Name": "李坤",  
  4.   "bir": "2012-06-22 21:26:40:592"  
  5. }  
  6. Json转为简单Bean===Student [birthDay=Fri Jun 22 21:26:40 CST 2012, id=0, name=李坤]  
  7. ----------带泛型的List之间的转化-------------  
  8. 带泛型的list转化为json==[  
  9.   {  
  10.     "Name": "李坤",  
  11.     "bir": "2012-06-22 21:26:40:592"  
  12.   },  
  13.   {  
  14.     "Name": "曹贵生",  
  15.     "bir": "2012-06-22 21:26:40:625"  
  16.   },  
  17.   {  
  18.     "Name": "柳波",  
  19.     "bir": "2012-06-22 21:26:40:625"  
  20.   }  
  21. ]  
  22. Student [birthDay=Fri Jun 22 21:26:40 CST 2012, id=0, name=李坤]  
  23. Student [birthDay=Fri Jun 22 21:26:40 CST 2012, id=0, name=曹贵生]  
  24. Student [birthDay=Fri Jun 22 21:26:40 CST 2012, id=0, name=柳波
Json转换利器Gson之实例三-Map处理(上) 

Map的存储结构式Key/Value形式,Key 和 Value可以是普通类型,也可以是自己写的JavaBean(本文),还可以是带有泛型的List(下一篇博客).本例中您要重点看如何将Json转回为普通JavaBean对象时TypeToken的定义.

实体类:

[java]  view plain copy
  1. public class Point {  
  2.     private int x;  
  3.     private int y;  
  4.   
  5.     public Point(int x, int y) {  
  6.         this.x = x;  
  7.         this.y = y;  
  8.     }  
  9.   
  10.     public int getX() {  
  11.         return x;  
  12.     }  
  13.   
  14.     public void setX(int x) {  
  15.         this.x = x;  
  16.     }  
  17.   
  18.     public int getY() {  
  19.         return y;  
  20.     }  
  21.   
  22.     public void setY(int y) {  
  23.         this.y = y;  
  24.     }  
  25.   
  26.     @Override  
  27.     public String toString() {  
  28.         return "Point [x=" + x + ", y=" + y + "]";  
  29.     }  
  30.   
  31. }  

测试类:

[java]  view plain copy
  1. import java.util.LinkedHashMap;  
  2. import java.util.Map;  
  3.   
  4. import com.google.gson.Gson;  
  5. import com.google.gson.GsonBuilder;  
  6. import com.google.gson.reflect.TypeToken;  
  7.   
  8. public class GsonTest3 {  
  9.   
  10.     public static void main(String[] args) {  
  11.         Gson gson = new GsonBuilder().enableComplexMapKeySerialization()  
  12.                 .create();  
  13.   
  14.         Map<Point, String> map1 = new LinkedHashMap<Point, String>();// 使用LinkedHashMap将结果按先进先出顺序排列  
  15.         map1.put(new Point(56), "a");  
  16.         map1.put(new Point(88), "b");  
  17.         String s = gson.toJson(map1);  
  18.         System.out.println(s);// 结果:[[{"x":5,"y":6},"a"],[{"x":8,"y":8},"b"]]  
  19.   
  20.         Map<Point, String> retMap = gson.fromJson(s,  
  21.                 new TypeToken<Map<Point, String>>() {  
  22.                 }.getType());  
  23.         for (Point p : retMap.keySet()) {  
  24.             System.out.println("key:" + p + " values:" + retMap.get(p));  
  25.         }  
  26.         System.out.println(retMap);  
  27.   
  28.         System.out.println("----------------------------------");  
  29.         Map<String, Point> map2 = new LinkedHashMap<String, Point>();  
  30.         map2.put("a"new Point(34));  
  31.         map2.put("b"new Point(56));  
  32.         String s2 = gson.toJson(map2);  
  33.         System.out.println(s2);  
  34.   
  35.         Map<String, Point> retMap2 = gson.fromJson(s2,  
  36.                 new TypeToken<Map<String, Point>>() {  
  37.                 }.getType());  
  38.         for (String key : retMap2.keySet()) {  
  39.             System.out.println("key:" + key + " values:" + retMap2.get(key));  
  40.         }  
  41.   
  42.     }  
  43. }  

结果:

[plain]  view plain copy
  1. [[{"x":5,"y":6},"a"],[{"x":8,"y":8},"b"]]  
  2. key:Point [x=5, y=6] values:a  
  3. key:Point [x=8, y=8] values:b  
  4. {Point [x=5, y=6]=a, Point [x=8, y=8]=b}  
  5. ----------------------------------  
  6. {"a":{"x":3,"y":4},"b":{"x":5,"y":6}}  
  7. key:a values:Point [x=3, y=4]  
Json转换利器Gson之实例四-Map处理(下) 

Map的存储结构式Key/Value形式,Key 和 Value可以是普通类型,也可以是自己写的JavaBean(上一篇博客),还可以是带有泛型的List(本文).本例中您要重点看如何将Json转回为带泛型的对象List,并且List中的泛型对象有多种实体.

实体类:

[java]  view plain copy
  1. import java.util.Date;  
  2.   
  3. public class Student {  
  4.     private int id;  
  5.     private String name;  
  6.     private Date birthDay;  
  7.   
  8.     public int getId() {  
  9.         return id;  
  10.     }  
  11.   
  12.     public void setId(int id) {  
  13.         this.id = id;  
  14.     }  
  15.   
  16.     public String getName() {  
  17.         return name;  
  18.     }  
  19.   
  20.     public void setName(String name) {  
  21.         this.name = name;  
  22.     }  
  23.   
  24.     public Date getBirthDay() {  
  25.         return birthDay;  
  26.     }  
  27.   
  28.     public void setBirthDay(Date birthDay) {  
  29.         this.birthDay = birthDay;  
  30.     }  
  31.   
  32.     @Override  
  33.     public String toString() {  
  34.         return "Student [birthDay=" + birthDay + ", id=" + id + ", name="  
  35.                 + name + "]";  
  36.     }  
  37.   
  38. }  

[java]  view plain copy
  1. public class Teacher {  
  2.     private int id;  
  3.   
  4.     private String name;  
  5.   
  6.     private String title;  
  7.   
  8.     public int getId() {  
  9.         return id;  
  10.     }  
  11.   
  12.     public void setId(int id) {  
  13.         this.id = id;  
  14.     }  
  15.   
  16.     public String getName() {  
  17.         return name;  
  18.     }  
  19.   
  20.     public void setName(String name) {  
  21.         this.name = name;  
  22.     }  
  23.   
  24.     public String getTitle() {  
  25.         return title;  
  26.     }  
  27.   
  28.     public void setTitle(String title) {  
  29.         this.title = title;  
  30.     }  
  31.   
  32.     @Override  
  33.     public String toString() {  
  34.         return "Teacher [id=" + id + ", name=" + name + ", title=" + title  
  35.                 + "]";  
  36.     }  
  37.   
  38. }  

测试类:

[java]  view plain copy
  1. package com.tgb.lk.demo.gson.test4;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.Date;  
  5. import java.util.LinkedHashMap;  
  6. import java.util.List;  
  7. import java.util.Map;  
  8.   
  9. import com.google.gson.Gson;  
  10. import com.google.gson.reflect.TypeToken;  
  11.   
  12. public class GsonTest4 {  
  13.     public static void main(String[] args) {  
  14.         Student student1 = new Student();  
  15.         student1.setId(1);  
  16.         student1.setName("李坤");  
  17.         student1.setBirthDay(new Date());  
  18.   
  19.         Student student2 = new Student();  
  20.         student2.setId(2);  
  21.         student2.setName("曹贵生");  
  22.         student2.setBirthDay(new Date());  
  23.   
  24.         Student student3 = new Student();  
  25.         student3.setId(3);  
  26.         student3.setName("柳波");  
  27.         student3.setBirthDay(new Date());  
  28.   
  29.         List<Student> stulist = new ArrayList<Student>();  
  30.         stulist.add(student1);  
  31.         stulist.add(student2);  
  32.         stulist.add(student3);  
  33.   
  34.         Teacher teacher1 = new Teacher();  
  35.         teacher1.setId(1);  
  36.         teacher1.setName("米老师");  
  37.         teacher1.setTitle("教授");  
  38.   
  39.         Teacher teacher2 = new Teacher();  
  40.         teacher2.setId(2);  
  41.         teacher2.setName("丁老师");  
  42.         teacher2.setTitle("讲师");  
  43.         List<Teacher> teacherList = new ArrayList<Teacher>();  
  44.         teacherList.add(teacher1);  
  45.         teacherList.add(teacher2);  
  46.   
  47.         Map<String, Object> map = new LinkedHashMap<String, Object>();  
  48.         map.put("students", stulist);  
  49.         map.put("teachers", teacherList);  
  50.   
  51.         Gson gson = new Gson();  
  52.         String s = gson.toJson(map);  
  53.         System.out.println(s);  
  54.   
  55.         System.out.println("----------------------------------");  
  56.   
  57.         Map<String, Object> retMap = gson.fromJson(s,  
  58.                 new TypeToken<Map<String, List<Object>>>() {  
  59.                 }.getType());  
  60.   
  61.         for (String key : retMap.keySet()) {  
  62.             System.out.println("key:" + key + " values:" + retMap.get(key));  
  63.             if (key.equals("students")) {  
  64.                 List<Student> stuList = (List<Student>) retMap.get(key);  
  65.                 System.out.println(stuList);  
  66.             } else if (key.equals("teachers")) {  
  67.                 List<Teacher> tchrList = (List<Teacher>) retMap.get(key);  
  68.                 System.out.println(tchrList);  
  69.             }  
  70.         }  
  71.   
  72.     }  
  73. }  

输出结果:

[plain]  view plain copy
  1. {"students":[{"id":1,"name":"李坤","birthDay":"Jun 22, 2012 9:48:19 PM"},{"id":2,"name":"曹贵生","birthDay":"Jun 22, 2012 9:48:19 PM"},{"id":3,"name":"柳波","birthDay":"Jun 22, 2012 9:48:19 PM"}],"teachers":[{"id":1,"name":"米老师","title":"教授"},{"id":2,"name":"丁老师","title":"讲师"}]}  
  2. ----------------------------------  
  3. key:students values:[{id=1.0, name=李坤, birthDay=Jun 22, 2012 9:48:19 PM}, {id=2.0, name=曹贵生, birthDay=Jun 22, 2012 9:48:19 PM}, {id=3.0, name=柳波, birthDay=Jun 22, 2012 9:48:19 PM}]  
  4. [{id=1.0, name=李坤, birthDay=Jun 22, 2012 9:48:19 PM}, {id=2.0, name=曹贵生, birthDay=Jun 22, 2012 9:48:19 PM}, {id=3.0, name=柳波, birthDay=Jun 22, 2012 9:48:19 PM}]  
  5. key:teachers values:[{id=1.0, name=米老师, title=教授}, {id=2.0, name=丁老师, title=讲师}]  
  6. [{id=1.0, name=米老师, title=教授}, {id=2.0, name=丁老师, title=讲师}]  
Json转换利器Gson之实例五-实际开发中的特殊需求处理 

前面四篇博客基本上可以满足我们处理的绝大多数需求,但有时项目中对json有特殊的格式规定.比如下面的json串解析:

[{"tableName":"students","tableData":[{"id":1,"name":"李坤","birthDay":"Jun 22, 2012 9:54:49 PM"},{"id":2,"name":"曹贵生","birthDay":"Jun 22, 2012 9:54:49 PM"},{"id":3,"name":"柳波","birthDay":"Jun 22, 2012 9:54:49 PM"}]},{"tableName":"teachers","tableData":[{"id":1,"name":"米老师","title":"教授"},{"id":2,"name":"丁老师","title":"讲师"}]}]

分析之后我们发现使用前面博客中用到的都不好处理上面的json串.请看本文是如何处理的吧:

实体类:

[java]  view plain copy
  1. import java.util.Date;  
  2.   
  3. public class Student {  
  4.     private int id;  
  5.     private String name;  
  6.     private Date birthDay;  
  7.   
  8.     public int getId() {  
  9.         return id;  
  10.     }  
  11.   
  12.     public void setId(int id) {  
  13.         this.id = id;  
  14.     }  
  15.   
  16.     public String getName() {  
  17.         return name;  
  18.     }  
  19.   
  20.     public void setName(String name) {  
  21.         this.name = name;  
  22.     }  
  23.   
  24.     public Date getBirthDay() {  
  25.         return birthDay;  
  26.     }  
  27.   
  28.     public void setBirthDay(Date birthDay) {  
  29.         this.birthDay = birthDay;  
  30.     }  
  31.   
  32.     @Override  
  33.     public String toString() {  
  34.         return "Student [birthDay=" + birthDay + ", id=" + id + ", name="  
  35.                 + name + "]";  
  36.     }  
  37.   
  38. }  

[java]  view plain copy
  1. public class Teacher {  
  2.     private int id;  
  3.   
  4.     private String name;  
  5.   
  6.     private String title;  
  7.   
  8.     public int getId() {  
  9.         return id;  
  10.     }  
  11.   
  12.     public void setId(int id) {  
  13.         this.id = id;  
  14.     }  
  15.   
  16.     public String getName() {  
  17.         return name;  
  18.     }  
  19.   
  20.     public void setName(String name) {  
  21.         this.name = name;  
  22.     }  
  23.   
  24.     public String getTitle() {  
  25.         return title;  
  26.     }  
  27.   
  28.     public void setTitle(String title) {  
  29.         this.title = title;  
  30.     }  
  31.   
  32.     @Override  
  33.     public String toString() {  
  34.         return "Teacher [id=" + id + ", name=" + name + ", title=" + title  
  35.                 + "]";  
  36.     }  
  37.   
  38. }  
注意这里定义了一个TableData实体类:

[java]  view plain copy
  1. import java.util.List;  
  2.   
  3. public class TableData {  
  4.   
  5.     private String tableName;  
  6.   
  7.     private List tableData;  
  8.   
  9.     public String getTableName() {  
  10.         return tableName;  
  11.     }  
  12.   
  13.     public void setTableName(String tableName) {  
  14.         this.tableName = tableName;  
  15.     }  
  16.   
  17.     public List getTableData() {  
  18.         return tableData;  
  19.     }  
  20.   
  21.     public void setTableData(List tableData) {  
  22.         this.tableData = tableData;  
  23.     }  
  24. }  

测试类:

(仔细看将json转回为对象的实现,这里经过两次转化,第一次转回的结果是map不是我们所期望的对象,对map再次转为json后再转为对象,我引用的是Gson2.1的jar处理正常,好像使用Gson1.6的jar会报错,所以建议用最新版本)

[java]  view plain copy
  1. import java.util.ArrayList;  
  2. import java.util.Date;  
  3. import java.util.List;  
  4.   
  5. import com.google.gson.Gson;  
  6. import com.google.gson.reflect.TypeToken;  
  7.   
  8. public class GsonTest5 {  
  9.   
  10.     /** 
  11.      * @param args 
  12.      */  
  13.     public static void main(String[] args) {  
  14.         // 对象转为Json-->start  
  15.         Student student1 = new Student();  
  16.         student1.setId(1);  
  17.         student1.setName("李坤");  
  18.         student1.setBirthDay(new Date());  
  19.   
  20.         Student student2 = new Student();  
  21.         student2.setId(2);  
  22.         student2.setName("曹贵生");  
  23.         student2.setBirthDay(new Date());  
  24.   
  25.         Student student3 = new Student();  
  26.         student3.setId(3);  
  27.         student3.setName("柳波");  
  28.         student3.setBirthDay(new Date());  
  29.   
  30.         List<Student> stulist = new ArrayList<Student>();  
  31.         stulist.add(student1);  
  32.         stulist.add(student2);  
  33.         stulist.add(student3);  
  34.   
  35.         Teacher teacher1 = new Teacher();  
  36.         teacher1.setId(1);  
  37.         teacher1.setName("米老师");  
  38.         teacher1.setTitle("教授");  
  39.   
  40.         Teacher teacher2 = new Teacher();  
  41.         teacher2.setId(2);  
  42.         teacher2.setName("丁老师");  
  43.         teacher2.setTitle("讲师");  
  44.         List<Teacher> teacherList = new ArrayList<Teacher>();  
  45.         teacherList.add(teacher1);  
  46.         teacherList.add(teacher2);  
  47.   
  48.         TableData td1 = new TableData();  
  49.         td1.setTableName("students");  
  50.         td1.setTableData(stulist);  
  51.   
  52.         TableData td2 = new TableData();  
  53.         td2.setTableName("teachers");  
  54.         td2.setTableData(teacherList);  
  55.   
  56.         List<TableData> tdList = new ArrayList<TableData>();  
  57.         tdList.add(td1);  
  58.         tdList.add(td2);  
  59.         Gson gson = new Gson();  
  60.         String s = gson.toJson(tdList);  
  61.   
  62.         System.out.println(s);  
  63.         // 结果:[{"tableName":"students","tableData":[{"id":1,"name":"李坤","birthDay":"Jun 22, 2012 10:44:16 AM"},{"id":2,"name":"曹贵生","birthDay":"Jun 22, 2012 10:44:16 AM"},{"id":3,"name":"柳波","birthDay":"Jun 22, 2012 10:44:16 AM"}]},{"tableName":"teachers","tableData":[{"id":1,"name":"米老师","title":"教授"},{"id":2,"name":"丁老师","title":"讲师"}]}]  
  64.         // 对象转为Json-->end  
  65.   
  66.         // /  
  67.   
  68.         // 将json转为数据-->start  
  69.         List<TableData> tableDatas2 = gson.fromJson(s,  
  70.                 new TypeToken<List<TableData>>() {  
  71.                 }.getType());  
  72.         for (int i = 0; i < tableDatas2.size(); i++) {  
  73.             TableData entityData = tableDatas2.get(i);  
  74.             String tableName = entityData.getTableName();  
  75.             List tableData = entityData.getTableData();  
  76.             String s2 = gson.toJson(tableData);  
  77.             // System.out.println(s2);  
  78.             // System.out.println(entityData.getData());  
  79.             if (tableName.equals("students")) {  
  80.                 System.out.println("students");  
  81.                 List<Student> retStuList = gson.fromJson(s2,  
  82.                         new TypeToken<List<Student>>() {  
  83.                         }.getType());  
  84.                 for (int j = 0; j < retStuList.size(); j++) {  
  85.                     System.out.println(retStuList.get(j));  
  86.                 }  
  87.   
  88.             } else if (tableName.equals("teachers")) {  
  89.                 System.out.println("teachers");  
  90.                 List<Teacher> retTchrList = gson.fromJson(s2,  
  91.                         new TypeToken<List<Teacher>>() {  
  92.                         }.getType());  
  93.                 for (int j = 0; j < retTchrList.size(); j++) {  
  94.                     System.out.println(retTchrList.get(j));  
  95.                 }  
  96.             }  
  97.         }  
  98.   
  99.         // Json转为对象-->end  
  100.     }  
  101. }  

输出结果:

[plain]  view plain copy
  1. [{"tableName":"students","tableData":[{"id":1,"name":"李坤","birthDay":"Jun 22, 2012 10:04:12 PM"},{"id":2,"name":"曹贵生","birthDay":"Jun 22, 2012 10:04:12 PM"},{"id":3,"name":"柳波","birthDay":"Jun 22, 2012 10:04:12 PM"}]},{"tableName":"teachers","tableData":[{"id":1,"name":"米老师","title":"教授"},{"id":2,"name":"丁老师","title":"讲师"}]}]  
  2. students  
  3. Student [birthDay=Fri Jun 22 22:04:12 CST 2012, id=1, name=李坤]  
  4. Student [birthDay=Fri Jun 22 22:04:12 CST 2012, id=2, name=曹贵生]  
  5. Student [birthDay=Fri Jun 22 22:04:12 CST 2012, id=3, name=柳波]  
  6. teachers  
  7. Teacher [id=1, name=米老师, title=教授]  
  8. Teacher [id=2, name=丁老师, title=讲师]  
Json转换利器Gson之实例六-注册TypeAdapter及处理Enum类型

枚举类型给我们的程序带来了好处,如何用Gson来实现与Json的互转呢?请看本文.

本文重点掌握如何自己写一个TypeAdapter及注册TypeAdapter和处理Enum类型.

实体类:

[java]  view plain copy
  1. public enum PackageState {  
  2.     PLAY, UPDATE, UPDATING, DOWNLOAD, DOWNLOADING,  
  3. }  

[java]  view plain copy
  1. public class PackageItem {  
  2.     private String name;  
  3.     private PackageState state;  
  4.     private String size;  
  5.   
  6.     public String getName() {  
  7.         return name;  
  8.     }  
  9.   
  10.     public void setName(String name) {  
  11.         this.name = name;  
  12.     }  
  13.   
  14.     public PackageState getState() {  
  15.         return state;  
  16.     }  
  17.   
  18.     public void setState(PackageState state) {  
  19.         this.state = state;  
  20.     }  
  21.   
  22.     public String getSize() {  
  23.         return size;  
  24.     }  
  25.   
  26.     public void setSize(String size) {  
  27.         this.size = size;  
  28.     }  
  29.   
  30.     @Override  
  31.     public String toString() {  
  32.         return "PackageItem [name=" + name + ", size=" + size + ", state="  
  33.                 + state + "]";  
  34.     }  
  35. }  

自己写一个转换器实现JsonSerializer<T>接口和jsonDeserializer<T>接口:

[java]  view plain copy
  1. mport java.lang.reflect.Type;  
  2.   
  3. import com.google.gson.JsonDeserializationContext;  
  4. import com.google.gson.JsonDeserializer;  
  5. import com.google.gson.JsonElement;  
  6. import com.google.gson.JsonParseException;  
  7. import com.google.gson.JsonPrimitive;  
  8. import com.google.gson.JsonSerializationContext;  
  9. import com.google.gson.JsonSerializer;  
  10.   
  11. public class EnumSerializer implements JsonSerializer<PackageState>,  
  12.         JsonDeserializer<PackageState> {  
  13.   
  14.     // 对象转为Json时调用,实现JsonSerializer<PackageState>接口  
  15.     @Override  
  16.     public JsonElement serialize(PackageState state, Type arg1,  
  17.             JsonSerializationContext arg2) {  
  18.         return new JsonPrimitive(state.ordinal());  
  19.     }  
  20.   
  21.     // json转为对象时调用,实现JsonDeserializer<PackageState>接口  
  22.     @Override  
  23.     public PackageState deserialize(JsonElement json, Type typeOfT,  
  24.             JsonDeserializationContext context) throws JsonParseException {  
  25.         if (json.getAsInt() < PackageState.values().length)  
  26.             return PackageState.values()[json.getAsInt()];  
  27.         return null;  
  28.     }  
  29.   
  30. }  
测试类:
[java]  view plain copy
  1. import com.google.gson.Gson;  
  2. import com.google.gson.GsonBuilder;  
  3.   
  4. public class GsonTest6 {  
  5.   
  6.     public static void main(String[] args) {  
  7.         GsonBuilder gsonBuilder = new GsonBuilder();  
  8.         gsonBuilder.registerTypeAdapter(PackageState.class,  
  9.                 new EnumSerializer());  
  10.         Gson gson = gsonBuilder.create();  
  11.         PackageItem item = new PackageItem();  
  12.         item.setName("item_name");  
  13.         item.setSize("500M");  
  14.         item.setState(PackageState.UPDATING);// 这个 state是枚举值  
  15.   
  16.         String s = gson.toJson(item);  
  17.         System.out.println(s);  
  18.   
  19.         System.out.println("--------------------------------");  
  20.   
  21.         PackageItem retItem = gson.fromJson(s, PackageItem.class);  
  22.         System.out.println(retItem);  
  23.     }  
  24. }  


输出结果(结果中已经将state的对应枚举类型转为了int类型):

[plain]  view plain copy
  1. {"name":"item_name","state":2,"size":"500M"}  
  2. --------------------------------  
  3. PackageItem [name=item_name, size=500M, state=UPDATING]  

Json转换利器Gson之实例一-简单对象转化和带泛型的List转化 (http://blog.csdn.net/lk_blog/article/details/7685169)
Json转换利器Gson之实例二-Gson注解和GsonBuilder (http://blog.csdn.net/lk_blog/article/details/7685190)
Json转换利器Gson之实例三-Map处理(上) (http://blog.csdn.net/lk_blog/article/details/7685210)
Json转换利器Gson之实例四-Map处理(下) (http://blog.csdn.net/lk_blog/article/details/7685224)
Json转换利器Gson之实例五-实际开发中的特殊需求处理 (http://blog.csdn.net/lk_blog/article/details/7685237)
Json转换利器Gson之实例六-注册TypeAdapter及处理Enum类型 (http://blog.csdn.net/lk_blog/article/details/7685347)

实例代码下载: http://download.csdn.net/detail/lk_blog/4387822


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在MATLAB中实现机械臂的仿真可以使用Robotic System Toolbox来进行。Robotic System Toolbox包含许多工具和函数,可以实现机械臂的建模、控制和仿真。 首先,需要定义机械臂的模型。可以使用robotics.RigidBodyTree类来创建机械臂的刚体树结构。通过添加关节和刚体可以构建机械臂的结构。可以使用函数robotics.RigidBody来创建刚体,并使用函数robotics.Joint来创建关节。 接下来,可以使用robotics.RigidBodyTree类中的函数来定义机械臂的初始状态。可以设置每个关节的初始位置和速度。 然后,可以使用robotics.RigidBodyTree类中的函数来进行机械臂的运动控制。可以使用函数robotics.InverseKinematics来实现逆运动学,根据目标位置和姿态来求解关节角度。可以使用函数robotics.CartesianTrajectory来生成机械臂的轨迹,指定起始和目标位置以及运动时间。 最后,可以使用robotics.RigidBodyTree类中的函数来进行机械臂的仿真。可以使用函数robotics.Rate来指定仿真的频率,然后使用循环来更新机械臂的状态和控制输入,实现机械臂的运动。 以下是一个基本的机械臂仿真的示例代码: ```matlab % 创建机械臂模型 robot = robotics.RigidBodyTree; % 添加机械臂的关节和刚体 % 设置机械臂的初始状态 % 运动控制 % 仿真循环 % 绘制机械臂的运动轨迹 ``` 在实际的机械臂仿真中,可能还需要考虑机械臂的动力学、碰撞检测和路径规划等问题。可以使用Robotic System Toolbox中的其他工具和函数来处理这些问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值