Android的Gson的使用方法,实现Json结构间相互转换

来源:互联网 发布:如何修改jenkins端口 编辑:程序博客网 时间:2024/05/22 02:28

一,把数组,对象,List,Map等数据结构转换成Json字符串

[java] view plain copy
 print?
  1. import java.lang.reflect.Type;  
  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.google.gson.Gson;  
  9. import com.google.gson.reflect.TypeToken;  
  10.   
  11.   
  12. public class Main {  
  13.   
  14.     public static class Student{  
  15.             private String name;  
  16.             int age;  
  17.             private String address;  
  18.               
  19.             private Date dateOfBirth;  
  20.             public Student() {  
  21.             }  
  22.             public Student(String name ,int age,String address, Date dateOfBirth) {  
  23.                 this.name = name;  
  24.                 this.age=age;  
  25.                 this.address = address;  
  26.                 this.dateOfBirth = dateOfBirth;  
  27.             }  
  28.               
  29.             public int getAge() {  
  30.                 return age;  
  31.             }  
  32.             public void setAge(int age) {  
  33.                 this.age = age;  
  34.             }  
  35.             public String getName() {  
  36.                 return name;  
  37.             }  
  38.             public void setName(String name) {  
  39.                 this.name = name;  
  40.             }  
  41.             public String getAddress() {  
  42.                 return address;  
  43.             }  
  44.             public void setAddress(String address) {  
  45.                 this.address = address;  
  46.             }  
  47.             public Date getDateOfBirth() {  
  48.                 return dateOfBirth;  
  49.             }  
  50.             public void setDateOfBirth(Date dateOfBirth) {  
  51.                 this.dateOfBirth = dateOfBirth;  
  52.             }  
  53.     }  
  54.     public static void main(String[] args) {  
  55.          Gson gson=new Gson();  
  56.           
  57.         /*数组转化成Json串*/  
  58.          int[] numbers = {11235813};  
  59.          String[] days = {"Sun""Mon""Tue""Wed""Thu""Fri""Sat"};  
  60.          String numbersJson=gson.toJson(numbers);  
  61.           String daysJson = gson.toJson(days);    
  62.           System.out.println("数组转化成Json字符串:");  
  63.           System.out.println("numbersJson = " + numbersJson);  
  64.           System.out.println("daysJson = " + daysJson);  
  65.            
  66.            
  67.          /*List转换成Json串,元素是字符串*/           
  68.          List<String> names = new ArrayList<String>();  
  69.             names.add("Alice");  
  70.             names.add("Bob");  
  71.             names.add("Carol");  
  72.             names.add("Mallory");  
  73.          String jsonNames = gson.toJson(names);  
  74.          System.out.println("List转换成Json串,元素是字符串");  
  75.          System.out.println("jsonNames = " + jsonNames);     
  76.            
  77.            
  78.          /*List转换成Json串,元素是对象*/       
  79.         Student a = new Student("Alice"20,"Apple St"new Date(2000101));  
  80.         Student b = new Student("Bob"23,"Banana St"null);  
  81.         Student c = new Student("Carol",42"Grape St"new Date(2000521));  
  82.         Student d = new Student("Mallory",24"Mango St"null);  
  83.   
  84.         List<Student> students = new ArrayList<Student>();  
  85.          students.add(a);  
  86.          students.add(b);  
  87.          students.add(c);  
  88.          students.add(d);  
  89.          String jsonStudents = gson.toJson(students);  
  90.          System.out.println("List转换成Json串,元素是对象");  
  91.          System.out.println("jsonStudents = " + jsonStudents);  
  92.          // Converts JSON string into a collection of Student object.         
  93.          Type type = new TypeToken<List<Student>>(){}.getType();  
  94.          System.out.println("Json串转换成List,元素是对象");  
  95.          List<Student> studentList = gson.fromJson(jsonStudents, type);  
  96.   
  97.          for (Student student : studentList) {  
  98.                 System.out.println("student.getName() = " + student.getName());  
  99.          }   
  100.            
  101.                    
  102.          /*Map转化成Json串,value是字符串*/  
  103.          Map<String, String> colors = new HashMap<String, String>();  
  104.             colors.put("BLACK""#000000");  
  105.             colors.put("RED""#FF0000");  
  106.             colors.put("GREEN""#008000");  
  107.             colors.put("BLUE""#0000FF");  
  108.             colors.put("YELLOW""#FFFF00");  
  109.             colors.put("WHITE""#FFFFFF");  
  110.               
  111.             String jsonmap = gson.toJson(colors);  
  112.             System.out.println("Map转化成Json串,value是字符串");  
  113.             System.out.println("json = " + jsonmap);  
  114.             // Convert JSON string back to Map.  
  115.             Type type1 = new TypeToken<Map<String, String>>(){}.getType();  
  116.             Map<String, String> map = gson.fromJson(jsonmap, type1);  
  117.             System.out.println("Json串转换成Map,value是字符串");  
  118.             for (String key : map.keySet()) {  
  119.                 System.out.println("map.get = " + map.get(key));  
  120.             }  
  121.               
  122.          /*Map转化成Json串,value是对象*/  
  123.          Map<String, Student> studentmap = new HashMap<String, Student>();  
  124.             studentmap.put("Alice", a);  
  125.             studentmap.put("Bob", b);  
  126.             studentmap.put("Carol", c);  
  127.             studentmap.put("Mallory", d);  
  128.   
  129.             String jsonmap1 = gson.toJson(studentmap);  
  130.             System.out.println("Map转化成Json串,value是对象");  
  131.             System.out.println("json = " + jsonmap1);  
  132.             // Convert JSON string back to Map.  
  133.             Type type11 = new TypeToken<Map<String, Student>>(){}.getType();  
  134.             System.out.println("Json串转换成Map,value是对象");  
  135.             Map<String, Student> map1 = gson.fromJson(jsonmap1, type11);  
  136.             for (String key : map1.keySet()) {  
  137.                 System.out.println("map1.get = " + map1.get(key).getName());  
  138.             }     
  139.                                                           
  140.     }  
  141.   
  142. }  
输出结果:

[java] view plain copy
 print?
  1. 数组转化成Json字符串:  
  2. numbersJson = [1,1,2,3,5,8,13]  
  3. daysJson = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]  
  4. List转换成Json串,元素是字符串  
  5. jsonNames = ["Alice","Bob","Carol","Mallory"]  
  6. List转换成Json串,元素是对象  
  7. jsonStudents = [{"name":"Alice","age":20,"address":"Apple St","dateOfBirth":"Nov 1, 3900 12:00:00 AM"},{"name":"Bob","age":23,"address":"Banana St"},{"name":"Carol","age":42,"address":"Grape St","dateOfBirth":"Jun 21, 3900 12:00:00 AM"},{"name":"Mallory","age":24,"address":"Mango St"}]  
  8. Json串转换成List,元素是对象  
  9. student.getName() = Alice  
  10. student.getName() = Bob  
  11. student.getName() = Carol  
  12. student.getName() = Mallory  
  13. Map转化成Json串,value是字符串  
  14. json = {"WHITE":"#FFFFFF","BLUE":"#0000FF","YELLOW":"#FFFF00","GREEN":"#008000","BLACK":"#000000","RED":"#FF0000"}  
  15. Json串转换成Map,value是字符串  
  16. map.get = #FFFFFF  
  17. map.get = #0000FF  
  18. map.get = #FFFF00  
  19. map.get = #008000  
  20. map.get = #000000  
  21. map.get = #FF0000  
  22. Map转化成Json串,value是对象  
  23. json = {"Mallory":{"name":"Mallory","age":24,"address":"Mango St"},"Alice":{"name":"Alice","age":20,"address":"Apple St","dateOfBirth":"Nov 1, 3900 12:00:00 AM"},"Bob":{"name":"Bob","age":23,"address":"Banana St"},"Carol":{"name":"Carol","age":42,"address":"Grape St","dateOfBirth":"Jun 21, 3900 12:00:00 AM"}}  
  24. Json串转换成Map,value是对象  
  25. map1.get = Mallory  
  26. map1.get = Alice  
  27. map1.get = Bob  
  28. map1.get = Carol  

可以观察到:

1,单个对象Object,Json串是一个JsonObject,冒号“:”前面的key是java对象的变量名,冒号“:”后面的Value是java对象的变量值

2,数组和List,Json串是一个JsonArray

3,Map的Json串是一个JsonObject,冒号“:”前面的key是Map的Key值,冒号“:”后面的Value是Map的Value值

二,Json串转换成Java对象时,主要看冒号“:”后面的Value的数据类型是什么,这样Java对象的字段类型就是什么,可以说Value的数据类型和字段的数据类型是对应的

[java] view plain copy
 print?
  1. {  
  2.     "success":true,  
  3.     "data":  
  4.       {  "list":  
  5.               [{"dataType":0,  
  6.                 "distance":435.2473470455821,  
  7.                 "isFav":0,"parkCode":"0270000558",  
  8.                 "parkName”:武汉金融港路场",  
  9. "parkID":558,  
  10. "remark":"",  
  11. "parkType":0,  
  12. "responsible":"",  
  13. "responseTel":"13297062676",  
  14. "consultTel":"",  
  15. "coordinateX":114.428102,  
  16. "coordinateY":30.462254,"  
  17. coordinateEntrance":"",  
  18. "rateInfo":"工作日",  
  19. "introduce":"",  
  20. "appState":3,  
  21. "paymentNoticeMinute":0,  
  22. "rentCount":0,  
  23. "rentSwitch":0,  
  24. "spaceCount":42,  
  25. "totalCount":42,  
  26. "imageName":"",  
  27. "fullImage":"",  
  28. "unitFee":0.0,  
  29. "unit":0,  
  30. "isRoadSide":0,  
  31. "rentOvertimeTimes":0.0,  
  32. "reservationKeepTime":0,  
  33. "supportPayType":0,  
  34. "address":"光谷大道金融港",  
  35. "state":1},  
  36.                  
  37. {"dataType":0,  
  38. "distance":568.3080108478586,  
  39. "isFav":0,  
  40. "parkCode":"0270000249",  
  41. "parkName":"武汉光谷金融港停车场",   
  42. "parkID":249,   
  43. "remark":"",   
  44. "parkType":3, "  
  45. “responsible":"",   
  46. "responseTel":"123456789",   
  47. "consultTel":"",   
  48. "coordinateX":114.427728,   
  49. "coordinateY":30.460922"coordinateEntrance":"114.427005,30.461393,1,1;114.427863,30.462163,1,1;114.428469,30.462171,1,1;114.427885,30.461404,2,1;114.428514,30.461424,2,1;114.428851,30.461397,3,1,1;114.427351,30.462163,3,1,1;",   
  50. "rateInfo":"白天3元/小时\n晚上1元/小时",  
  51. "introduce":"",  
  52. "appState":15,  
  53. "paymentNoticeMinute":2,  
  54. "rentCount":0,    
  55. "rentSwitch":1,  
  56. "spaceCount":-95,  
  57. "totalCount":300,  
  58. "imageName":"7.jpg",  
  59. "fullImage":"/picture/park/249/7.jpg",  
  60. "unitFee":0.01,  
  61. "unit":20,  
  62. "isRoadSide":0,  
  63. "rentOvertimeTimes":0.0,  
  64. "reservationKeepTime":0,  
  65. "supportPayType":0,  
  66. "address":"武汉市光谷金融港\n武汉市光谷金融港B4座12层",  
  67. "state":1  
  68. }    ]  
  69.         }  
  70. }  
[java] view plain copy
 print?
  1. package com.hust.map;  
  2.   
  3. public class Park {  
  4.            
  5.      int dataType;  
  6.      int rentCount;  
  7.      int parkCode;  
  8.      String parkName;   //停车场名字  
  9.      int parkID;  
  10.      String remark;  
  11.      int parkType;  
  12.      String responsible;  
  13.      String responseTel;  
  14.      String consultTel;  
  15.      double coordinateX;//经度  
  16.      double coordinateY;//纬度      
  17.      String coordinateEntrance;  
  18.      String rateInfo;   //收费标准  
  19.      String  introduce;  
  20.      int appState;  
  21.      int paymentNoticeMinute;  
  22.      int spaceCount;    //可租车位  
  23.      int totalCount;    //总车位  
  24.      String imageName;  
  25.      String fullImage;  
  26.      int reservationKeepTime;  
  27.      int isRoadSide;  
  28.      double rentOvertimeTimes;  
  29.      double unitFee;  
  30.      int unit;  
  31.      int rentSwitch;  
  32.      int supportPayType;  
  33.      int isFav;  
  34.      double distance;       //距离  
  35.      String address;    //地址  
  36.      int state;  
  37.        
  38.     public double getCoordinateX() {  
  39.         return coordinateX;  
  40.     }  
  41.     public void setCoordinateX(double coordinateX) {  
  42.         this.coordinateX = coordinateX;  
  43.     }  
  44.     public double getCoordinateY() {  
  45.         return coordinateY;  
  46.     }  
  47.     public void setCoordinateY(double coordinateY) {  
  48.         this.coordinateY = coordinateY;  
  49.     }  
  50.     public String getParkName() {  
  51.         return parkName;  
  52.     }  
  53.     public void setParkName(String parkName) {  
  54.         this.parkName = parkName;  
  55.     }  
  56.     public int getSpaceCount() {  
  57.         return spaceCount;  
  58.     }  
  59.     public void setSpaceCount(int spaceCount) {  
  60.         this.spaceCount = spaceCount;  
  61.     }  
  62.     public int getTotalCount() {  
  63.         return totalCount;  
  64.     }  
  65.     public void setTotalCount(int totalCount) {  
  66.         this.totalCount = totalCount;  
  67.     }  
  68.     public String getRateInfo() {  
  69.         return rateInfo;  
  70.     }  
  71.     public void setRateInfo(String rateInfo) {  
  72.         this.rateInfo = rateInfo;  
  73.     }  
  74.     public double getDistance() {  
  75.         return distance;  
  76.     }  
  77.     public void setDistance(double distance) {  
  78.         this.distance = distance;  
  79.     }  
  80.     public String getAddress() {  
  81.         return address;  
  82.     }  
  83.     public void setAddress(String address) {  
  84.         this.address = address;  
  85.     }  
  86.     public Park(int dataType, int rentCount, int parkCode, String parkName,  
  87.             int parkID, String remark, int parkType, String responsible,  
  88.             String responseTel, String consultTel, double coordinateX,  
  89.             double coordinateY, String coordinateEntrance, String rateInfo,  
  90.             String introduce, int appState, int paymentNoticeMinute,  
  91.             int spaceCount, int totalCount, String imageName, String fullImage,  
  92.             int reservationKeepTime, int isRoadSide, double rentOvertimeTimes,  
  93.             double unitFee, int unit, int rentSwitch, int supportPayType,  
  94.             int isFav, double distance, String address, int state) {  
  95.         super();  
  96.         this.dataType = dataType;  
  97.         this.rentCount = rentCount;  
  98.         this.parkCode = parkCode;  
  99.         this.parkName = parkName;  
  100.         this.parkID = parkID;  
  101.         this.remark = remark;  
  102.         this.parkType = parkType;  
  103.         this.responsible = responsible;  
  104.         this.responseTel = responseTel;  
  105.         this.consultTel = consultTel;  
  106.         this.coordinateX = coordinateX;  
  107.         this.coordinateY = coordinateY;  
  108.         this.coordinateEntrance = coordinateEntrance;  
  109.         this.rateInfo = rateInfo;  
  110.         this.introduce = introduce;  
  111.         this.appState = appState;  
  112.         this.paymentNoticeMinute = paymentNoticeMinute;  
  113.         this.spaceCount = spaceCount;  
  114.         this.totalCount = totalCount;  
  115.         this.imageName = imageName;  
  116.         this.fullImage = fullImage;  
  117.         this.reservationKeepTime = reservationKeepTime;  
  118.         this.isRoadSide = isRoadSide;  
  119.         this.rentOvertimeTimes = rentOvertimeTimes;  
  120.         this.unitFee = unitFee;  
  121.         this.unit = unit;  
  122.         this.rentSwitch = rentSwitch;  
  123.         this.supportPayType = supportPayType;  
  124.         this.isFav = isFav;  
  125.         this.distance = distance;  
  126.         this.address = address;  
  127.         this.state = state;  
  128.     }  
  129.     public int getDataType() {  
  130.         return dataType;  
  131.     }  
  132.     public void setDataType(int dataType) {  
  133.         this.dataType = dataType;  
  134.     }  
  135.     public int getRentCount() {  
  136.         return rentCount;  
  137.     }  
  138.     public void setRentCount(int rentCount) {  
  139.         this.rentCount = rentCount;  
  140.     }  
  141.     public int getParkCode() {  
  142.         return parkCode;  
  143.     }  
  144.     public void setParkCode(int parkCode) {  
  145.         this.parkCode = parkCode;  
  146.     }  
  147.     public int getParkID() {  
  148.         return parkID;  
  149.     }  
  150.     public void setParkID(int parkID) {  
  151.         this.parkID = parkID;  
  152.     }  
  153.     public String getRemark() {  
  154.         return remark;  
  155.     }  
  156.     public void setRemark(String remark) {  
  157.         this.remark = remark;  
  158.     }  
  159.     public int getParkType() {  
  160.         return parkType;  
  161.     }  
  162.     public void setParkType(int parkType) {  
  163.         this.parkType = parkType;  
  164.     }  
  165.     public String getResponsible() {  
  166.         return responsible;  
  167.     }  
  168.     public void setResponsible(String responsible) {  
  169.         this.responsible = responsible;  
  170.     }  
  171.     public String getResponseTel() {  
  172.         return responseTel;  
  173.     }  
  174.     public void setResponseTel(String responseTel) {  
  175.         this.responseTel = responseTel;  
  176.     }  
  177.     public String getConsultTel() {  
  178.         return consultTel;  
  179.     }  
  180.     public void setConsultTel(String consultTel) {  
  181.         this.consultTel = consultTel;  
  182.     }  
  183.     public String getCoordinateEntrance() {  
  184.         return coordinateEntrance;  
  185.     }  
  186.     public void setCoordinateEntrance(String coordinateEntrance) {  
  187.         this.coordinateEntrance = coordinateEntrance;  
  188.     }  
  189.     public String getIntroduce() {  
  190.         return introduce;  
  191.     }  
  192.     public void setIntroduce(String introduce) {  
  193.         this.introduce = introduce;  
  194.     }  
  195.     public int getAppState() {  
  196.         return appState;  
  197.     }  
  198.     public void setAppState(int appState) {  
  199.         this.appState = appState;  
  200.     }  
  201.     public int getPaymentNoticeMinute() {  
  202.         return paymentNoticeMinute;  
  203.     }  
  204.     public void setPaymentNoticeMinute(int paymentNoticeMinute) {  
  205.         this.paymentNoticeMinute = paymentNoticeMinute;  
  206.     }  
  207.     public String getImageName() {  
  208.         return imageName;  
  209.     }  
  210.     public void setImageName(String imageName) {  
  211.         this.imageName = imageName;  
  212.     }  
  213.     public String getFullImage() {  
  214.         return fullImage;  
  215.     }  
  216.     public void setFullImage(String fullImage) {  
  217.         this.fullImage = fullImage;  
  218.     }  
  219.     public int getReservationKeepTime() {  
  220.         return reservationKeepTime;  
  221.     }  
  222.     public void setReservationKeepTime(int reservationKeepTime) {  
  223.         this.reservationKeepTime = reservationKeepTime;  
  224.     }  
  225.     public int getIsRoadSide() {  
  226.         return isRoadSide;  
  227.     }  
  228.     public void setIsRoadSide(int isRoadSide) {  
  229.         this.isRoadSide = isRoadSide;  
  230.     }  
  231.     public double getRentOvertimeTimes() {  
  232.         return rentOvertimeTimes;  
  233.     }  
  234.     public void setRentOvertimeTimes(double rentOvertimeTimes) {  
  235.         this.rentOvertimeTimes = rentOvertimeTimes;  
  236.     }  
  237.     public double getUnitFee() {  
  238.         return unitFee;  
  239.     }  
  240.     public void setUnitFee(double unitFee) {  
  241.         this.unitFee = unitFee;  
  242.     }  
  243.     public int getUnit() {  
  244.         return unit;  
  245.     }  
  246.     public void setUnit(int unit) {  
  247.         this.unit = unit;  
  248.     }  
  249.     public int getRentSwitch() {  
  250.         return rentSwitch;  
  251.     }  
  252.     public void setRentSwitch(int rentSwitch) {  
  253.         this.rentSwitch = rentSwitch;  
  254.     }  
  255.     public int getSupportPayType() {  
  256.         return supportPayType;  
  257.     }  
  258.     public void setSupportPayType(int supportPayType) {  
  259.         this.supportPayType = supportPayType;  
  260.     }  
  261.     public int getIsFav() {  
  262.         return isFav;  
  263.     }  
  264.     public void setIsFav(int isFav) {  
  265.         this.isFav = isFav;  
  266.     }  
  267.     public int getState() {  
  268.         return state;  
  269.     }  
  270.     public void setState(int state) {  
  271.         this.state = state;  
  272.     }  
  273.            
  274. }  
DataFromNetwork.java

[java] view plain copy
 print?
  1. package com.hust.map;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.HashMap;  
  5. public class DataFromNetWork {  
  6.       boolean success;  
  7.       HashMap<String,ArrayList<Park>> data;  
  8. }  


[java] view plain copy
 print?
  1. DataFromNetWork mDataFromNetWork=mGson.fromJson(mParksString, DataFromNetWork.class);  
  2.      ArrayList<Park> mParksList=mDataFromNetWork.data.get("list");  
阅读全文
1 0