Android用GSon处理Json数据

目前解析json有三种工具:org.json(Java常用的解析),fastjson(阿里巴巴工程师开发的),Gson(Google官网出的),解析速度最快的是Gson,下载地址:https://code.google.com/p/google-gson/


什么是JSON:


JSON即JavaScript Object Natation, 它是一种轻量级的数据交换格式, 与XML一样, 是广泛被采用的客户端和服务端交互的解决方案.


JSON对象: 


JSON中对象(Object)以"{"开始, 以"}"结束. 对象中的每一个item都是一个key-value对, 表现为"key:value"的形式, key-value对之间使用逗号分隔. 如:{"name":"coolxing", "age"=24, "male":true, "address":{"street":"huiLongGuan", "city":"beijing", "country":"china"}}. JSON对象的key只能是string类型的, 而value可以是string, number, false, true, null, Object对象甚至是array数组, 也就是说可以存在嵌套的情况.


JSON数组: 


JSON数组(array)以"["开始, 以"]"结束, 数组中的每一个元素可以是string, number, false, true, null, Object对象甚至是array数组, 数组间的元素使用逗号分隔. 如["coolxing", 24, {"street":"huiLongGuan", "city":"beijing", "country":"china"}].


Gson的基本使用方法:

通过获取JsonReader对象解析JSON数据:

String jsonData = "[{\"username\":\"arthinking\",\"userId\":001},{\"username\":\"Jason\",\"userId\":002}]";
try{
	JsonReader reader = new JsonReader(new StringReader(jsonData));
	reader.beginArray();
	while(reader.hasNext()){
		reader.beginObject();
		while(reader.hasNext()){
			String tagName = reader.nextName();
			if(tagName.equals("username")){
				System.out.println(reader.nextString());
			}
			else if(tagName.equals("userId")){
				System.out.println(reader.nextString());
			}
		}
		reader.endObject();
	}
	reader.endArray();
}
catch(Exception e){
	e.printStackTrace();
}

 
  

通过把JSON数据映射成一个对象,使用Gson对象的fromJson()方法获取一个对象数组进行操作:

创建JSON数据对应的一个POJO对象User.java:

public class User {
	private String username ;
	private int userId ;
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public int getUserId() {
		return userId;
	}
	public void setUserId(int userId) {
		this.userId = userId;
	}
}

使用Gson对象获取User对象数据进行相应的操作:

Type listType = new TypeToken>(){}.getType();
Gson gson = new Gson();
LinkedList users = gson.fromJson(jsonData, listType);
for (Iterator iterator = users.iterator(); iterator.hasNext();) {
	User user = (User) iterator.next();
	System.out.println(user.getUsername());
	System.out.println(user.getUserId());
}

如果要处理的JSON字符串只包含一个JSON对象,则可以直接使用fromJson获取一个User对象:

String jsonData = "{\"username\":\"arthinking\",\"userId\":001}";
Gson gson = new Gson();
User user = gson.fromJson(jsonData, User.class);
System.out.println(user.getUsername());
System.out.println(user.getUserId());
解析复杂实例:

数据格式:

[java]  view plain copy
  1. {  
  2.     "data": {  
  3.         "partnerteamlist": [  
  4.             {  
  5.                 "pteamId"72825,  
  6.                 "ptitle""随摄影/共6套服装/准爸准妈共拍/免费肚画/底片全送。",  
  7.                 "pteamprice"288  
  8.             },  
  9.             {  
  10.                 "pteamId"72598,  
  11.                 "ptitle""随摄影/拍摄200张/4本相册/品质拍摄/送全新婚纱。",  
  12.                 "pteamprice"2888  
  13.             },  
  14.             {  
  15.                 "pteamId"72613,  
  16.                 "ptitle""随摄影/送全新婚纱/多外景拍摄/服装不限数量/绝无二次消费!",  
  17.                 "pteamprice"3699  
  18.             },  
  19.             {  
  20.                 "pteamId"72638,  
  21.                 "ptitle""随摄影/服装不限数量/高品质拍摄260张/送全新婚纱。",  
  22.                 "pteamprice"4299  
  23.             },  
  24.             {  
  25.                 "pteamId"72716,  
  26.                 "ptitle""随摄影/3组服装造型/内外景拍摄/完全透明消费!",  
  27.                 "pteamprice"388  
  28.             }  
  29.         ],  
  30.         "liketeamlist": [  
  31.             {  
  32.                 "lteamId"65886,  
  33.                 "ltitle""爱丽尔婚纱摄影/2本相册/6套服装造型/拍摄不限最低拍摄150张。",  
  34.                 "limage""http://img.pztuan.com/upfile/team/2013/0712/201307120257551465.jpg",  
  35.                 "lteamprice"518,  
  36.                 "lmarketprice"3999  
  37.             },  
  38.             {  
  39.                 "lteamId"57133,  
  40.                 "ltitle""陶冶摄影/婚纱闺蜜/6组服装造型/拍摄不低于120张!",  
  41.                 "limage""http://img.pztuan.com/upfile/team/2013/0628/201306281115249737.jpg",  
  42.                 "lteamprice"580,  
  43.                 "lmarketprice"3380  
  44.             }  
  45.         ],  
  46.         "feedbacks": {  
  47.             "feedbacklist": [  
  48.                 {  
  49.                     "comment""5分",  
  50.                     "createtime""2014.07.08 13:38",  
  51.                     "score"5,  
  52.                     "username""l***2"  
  53.                 }  
  54.             ],  
  55.             "totalcount"1,  
  56.             "totalscore"5  
  57.         }  
  58.     },  
  59.     "err"null,  
  60.     "state"1  
  61. }  

实体类(里面的成员变量和接口的返回值名称一 一对应才能保证解析正确):

[java]  view plain copy
  1. package com.pztuan.entity;  
  2.   
  3. import java.util.List;  
  4.   
  5. public class OtherDetail {  
  6.   
  7.     private int state;  
  8.     private List err;  
  9.     private OtherDetail2 data;  
  10.   
  11.     public int getState() {  
  12.         return state;  
  13.     }  
  14.   
  15.     public void setState(int state) {  
  16.         this.state = state;  
  17.     }  
  18.   
  19.     public List getErr() {  
  20.         return err;  
  21.     }  
  22.   
  23.     public void setErr(List err) {  
  24.         this.err = err;  
  25.     }  
  26.   
  27.     public OtherDetail2 getData() {  
  28.         return data;  
  29.     }  
  30.   
  31.     public void setData(OtherDetail2 data) {  
  32.         this.data = data;  
  33.     }  
  34.   
  35.     public class OtherDetail2 {  
  36.         private List partnerteamlist;  
  37.         private List liketeamlist;  
  38.         private List feedbacks;  
  39.   
  40.         public List getLiketeamlist() {  
  41.             return liketeamlist;  
  42.         }  
  43.   
  44.         public void setLiketeamlist(List liketeamlist) {  
  45.             this.liketeamlist = liketeamlist;  
  46.         }  
  47.   
  48.         public List getFeedbacks() {  
  49.             return feedbacks;  
  50.         }  
  51.   
  52.         public void setFeedbacks(List feedbacks) {  
  53.             this.feedbacks = feedbacks;  
  54.         }  
  55.   
  56.         public class partnerteamlist {  
  57.             private int pteamId;  
  58.             private String ptitle;  
  59.             private Double pteamprice;  
  60.   
  61.             public int getPteamId() {  
  62.                 return pteamId;  
  63.             }  
  64.   
  65.             public void setPteamId(int pteamId) {  
  66.                 this.pteamId = pteamId;  
  67.             }  
  68.   
  69.             public String getPtitle() {  
  70.                 return ptitle;  
  71.             }  
  72.   
  73.             public void setPtitle(String ptitle) {  
  74.                 this.ptitle = ptitle;  
  75.             }  
  76.   
  77.             public Double getPteamprice() {  
  78.                 return pteamprice;  
  79.             }  
  80.   
  81.             public void setPteamprice(Double pteamprice) {  
  82.                 this.pteamprice = pteamprice;  
  83.             }  
  84.   
  85.         }  
  86.   
  87.         public class liketeamlist {  
  88.             private int lteamId;  
  89.             private String ltitle;  
  90.             private String limage;  
  91.             private Double lteamprice;  
  92.             private Double lmarketprice;  
  93.   
  94.             public int getLteamId() {  
  95.                 return lteamId;  
  96.             }  
  97.   
  98.             public void setLteamId(int lteamId) {  
  99.                 this.lteamId = lteamId;  
  100.             }  
  101.   
  102.             public String getLtitle() {  
  103.                 return ltitle;  
  104.             }  
  105.   
  106.             public void setLtitle(String ltitle) {  
  107.                 this.ltitle = ltitle;  
  108.             }  
  109.   
  110.             public String getLimage() {  
  111.                 return limage;  
  112.             }  
  113.   
  114.             public void setLimage(String limage) {  
  115.                 this.limage = limage;  
  116.             }  
  117.   
  118.             public Double getLteamprice() {  
  119.                 return lteamprice;  
  120.             }  
  121.   
  122.             public void setLteamprice(Double lteamprice) {  
  123.                 this.lteamprice = lteamprice;  
  124.             }  
  125.   
  126.             public Double getLmarketprice() {  
  127.                 return lmarketprice;  
  128.             }  
  129.   
  130.             public void setLmarketprice(Double lmarketprice) {  
  131.                 this.lmarketprice = lmarketprice;  
  132.             }  
  133.         }  
  134.   
  135.         public class feedbacks {  
  136.             private int totalcount;  
  137.             private Double totalscore;  
  138.             private List feedbacklist;  
  139.   
  140.             public int getTotalcount() {  
  141.                 return totalcount;  
  142.             }  
  143.   
  144.             public void setTotalcount(int totalcount) {  
  145.                 this.totalcount = totalcount;  
  146.             }  
  147.   
  148.             public Double getTotalscore() {  
  149.                 return totalscore;  
  150.             }  
  151.   
  152.             public void setTotalscore(Double totalscore) {  
  153.                 this.totalscore = totalscore;  
  154.             }  
  155.   
  156.             public List getFeedbacklist() {  
  157.                 return feedbacklist;  
  158.             }  
  159.   
  160.             public void setFeedbacklist(List feedbacklist) {  
  161.                 this.feedbacklist = feedbacklist;  
  162.             }  
  163.   
  164.             public class feedbacklist {  
  165.                 private String username;  
  166.                 private String comment;  
  167.                 private String createtime;  
  168.                 private Double score;  
  169.   
  170.                 public String getUsername() {  
  171.                     return username;  
  172.                 }  
  173.   
  174.                 public void setUsername(String username) {  
  175.                     this.username = username;  
  176.                 }  
  177.   
  178.                 public String getComment() {  
  179.                     return comment;  
  180.                 }  
  181.   
  182.                 public void setComment(String comment) {  
  183.                     this.comment = comment;  
  184.                 }  
  185.   
  186.                 public String getCreatetime() {  
  187.                     return createtime;  
  188.                 }  
  189.   
  190.                 public void setCreatetime(String createtime) {  
  191.                     this.createtime = createtime;  
  192.                 }  
  193.   
  194.                 public Double getScore() {  
  195.                     return score;  
  196.                 }  
  197.   
  198.                 public void setScore(Double score) {  
  199.                     this.score = score;  
  200.                 }  
  201.   
  202.             }  
  203.         }  
  204.   
  205.         public List getPartnerteamlist() {  
  206.             return partnerteamlist;  
  207.         }  
  208.   
  209.         public void setPartnerteamlist(List partnerteamlist) {  
  210.             this.partnerteamlist = partnerteamlist;  
  211.         }  
  212.     }  
  213.   
  214.     public class err {  
  215.         private int code;  
  216.         private String msg;  
  217.   
  218.         public int getCode() {  
  219.             return code;  
  220.         }  
  221.   
  222.         public void setCode(int code) {  
  223.             this.code = code;  
  224.         }  
  225.   
  226.         public String getMsg() {  
  227.             return msg;  
  228.         }  
  229.   
  230.         public void setMsg(String msg) {  
  231.             this.msg = msg;  
  232.         }  
  233.     }  
  234. }  

注意上面内部类的运用。

解析:

[java]  view plain copy
  1. Gson gson = new Gson();  
  2. OtherDetail d = gson.fromJson(jsonString,Detail.class);//取值的时候就从父类一层一层调子类成员(重要)  

若出现引用异常,请查看Java内部类设计原则。


参考:http://www.itzhai.com/android-to-parse-json-data-using-gson.html

           http://blog.csdn.net/caijunjun1006/article/details/11762841

在Android中可以使用Gson解析JSON数据

首先,从 code.google.com/p/google-gson/downloads/list下载GsonAPI:

google-gson-1.7.1-release.zip

把gson-1.7.jar copy到libs(项目根目录新建一个libs文件夹)中。

可以使用以下两种方法解析JSON数据:

通过获取JsonReader对象解析JSON数据:

String jsonData = "[{\"username\":\"arthinking\",\"userId\":001},{\"username\":\"Jason\",\"userId\":002}]";
try{
	JsonReader reader = new JsonReader(new StringReader(jsonData));
	reader.beginArray();
	while(reader.hasNext()){
		reader.beginObject();
		while(reader.hasNext()){
			String tagName = reader.nextName();
			if(tagName.equals("username")){
				System.out.println(reader.

你可能感兴趣的:(mozilla,json,sun公司,数据结构,javabean)