Android(安卓)Gson深入分析
Android Gson深入分析
目前解析json有三种工具:org.json(Java常用的解析),fastjson(阿里巴巴工程师开发的),Gson(Google官网出的),解析速度最快的是Gson,下载地址:https://code.google.com/p/google-gson/
什么是JSON:
JSON即JavaScriptObject 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<LinkedList<User>>(){}.getType();Gson gson = new Gson();LinkedList<User> 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 print ?
- {
- "data":{
- "partnerteamlist":[
- {
- "pteamId":72825,
- "ptitle":"随摄影/共6套服装/准爸准妈共拍/免费肚画/底片全送。",
- "pteamprice":288
- },
- {
- "pteamId":72598,
- "ptitle":"随摄影/拍摄200张/4本相册/品质拍摄/送全新婚纱。",
- "pteamprice":2888
- },
- {
- "pteamId":72613,
- "ptitle":"随摄影/送全新婚纱/多外景拍摄/服装不限数量/绝无二次消费!",
- "pteamprice":3699
- },
- {
- "pteamId":72638,
- "ptitle":"随摄影/服装不限数量/高品质拍摄260张/送全新婚纱。",
- "pteamprice":4299
- },
- {
- "pteamId":72716,
- "ptitle":"随摄影/3组服装造型/内外景拍摄/完全透明消费!",
- "pteamprice":388
- }
- ],
- "liketeamlist":[
- {
- "lteamId":65886,
- "ltitle":"爱丽尔婚纱摄影/2本相册/6套服装造型/拍摄不限最低拍摄150张。",
- "limage":"http://img.pztuan.com/upfile/team/2013/0712/201307120257551465.jpg",
- "lteamprice":518,
- "lmarketprice":3999
- },
- {
- "lteamId":57133,
- "ltitle":"陶冶摄影/婚纱闺蜜/6组服装造型/拍摄不低于120张!",
- "limage":"http://img.pztuan.com/upfile/team/2013/0628/201306281115249737.jpg",
- "lteamprice":580,
- "lmarketprice":3380
- }
- ],
- "feedbacks":{
- "feedbacklist":[
- {
- "comment":"5分",
- "createtime":"2014.07.0813:38",
- "score":5,
- "username":"l***2"
- }
- ],
- "totalcount":1,
- "totalscore":5
- }
- },
- "err":null,
- "state":1
- }
实体类(里面的成员变量和接口的返回值名称一 一对应才能保证解析正确):
[java] view plain copy print ?
- packagecom.pztuan.entity;
- importjava.util.List;
- publicclassOtherDetail{
- privateintstate;
- privateList<err>err;
- privateOtherDetail2data;
- publicintgetState(){
- returnstate;
- }
- publicvoidsetState(intstate){
- this.state=state;
- }
- publicList<err>getErr(){
- returnerr;
- }
- publicvoidsetErr(List<err>err){
- this.err=err;
- }
- publicOtherDetail2getData(){
- returndata;
- }
- publicvoidsetData(OtherDetail2data){
- this.data=data;
- }
- publicclassOtherDetail2{
- privateList<partnerteamlist>partnerteamlist;
- privateList<liketeamlist>liketeamlist;
- privateList<feedbacks>feedbacks;
- publicList<liketeamlist>getLiketeamlist(){
- returnliketeamlist;
- }
- publicvoidsetLiketeamlist(List<liketeamlist>liketeamlist){
- this.liketeamlist=liketeamlist;
- }
- publicList<feedbacks>getFeedbacks(){
- returnfeedbacks;
- }
- publicvoidsetFeedbacks(List<feedbacks>feedbacks){
- this.feedbacks=feedbacks;
- }
- publicclasspartnerteamlist{
- privateintpteamId;
- privateStringptitle;
- privateDoublepteamprice;
- publicintgetPteamId(){
- returnpteamId;
- }
- publicvoidsetPteamId(intpteamId){
- this.pteamId=pteamId;
- }
- publicStringgetPtitle(){
- returnptitle;
- }
- publicvoidsetPtitle(Stringptitle){
- this.ptitle=ptitle;
- }
- publicDoublegetPteamprice(){
- returnpteamprice;
- }
- publicvoidsetPteamprice(Doublepteamprice){
- this.pteamprice=pteamprice;
- }
- }
- publicclassliketeamlist{
- privateintlteamId;
- privateStringltitle;
- privateStringlimage;
- privateDoublelteamprice;
- privateDoublelmarketprice;
- publicintgetLteamId(){
- returnlteamId;
- }
- publicvoidsetLteamId(intlteamId){
- this.lteamId=lteamId;
- }
- publicStringgetLtitle(){
- returnltitle;
- }
- publicvoidsetLtitle(Stringltitle){
- this.ltitle=ltitle;
- }
- publicStringgetLimage(){
- returnlimage;
- }
- publicvoidsetLimage(Stringlimage){
- this.limage=limage;
- }
- publicDoublegetLteamprice(){
- returnlteamprice;
- }
- publicvoidsetLteamprice(Doublelteamprice){
- this.lteamprice=lteamprice;
- }
- publicDoublegetLmarketprice(){
- returnlmarketprice;
- }
- publicvoidsetLmarketprice(Doublelmarketprice){
- this.lmarketprice=lmarketprice;
- }
- }
- publicclassfeedbacks{
- privateinttotalcount;
- privateDoubletotalscore;
- privateList<feedbacklist>feedbacklist;
- publicintgetTotalcount(){
- returntotalcount;
- }
- publicvoidsetTotalcount(inttotalcount){
- this.totalcount=totalcount;
- }
- publicDoublegetTotalscore(){
- returntotalscore;
- }
- publicvoidsetTotalscore(Doubletotalscore){
- this.totalscore=totalscore;
- }
- publicList<feedbacklist>getFeedbacklist(){
- returnfeedbacklist;
- }
- publicvoidsetFeedbacklist(List<feedbacklist>feedbacklist){
- this.feedbacklist=feedbacklist;
- }
- publicclassfeedbacklist{
- privateStringusername;
- privateStringcomment;
- privateStringcreatetime;
- privateDoublescore;
- publicStringgetUsername(){
- returnusername;
- }
- publicvoidsetUsername(Stringusername){
- this.username=username;
- }
- publicStringgetComment(){
- returncomment;
- }
- publicvoidsetComment(Stringcomment){
- this.comment=comment;
- }
- publicStringgetCreatetime(){
- returncreatetime;
- }
- publicvoidsetCreatetime(Stringcreatetime){
- this.createtime=createtime;
- }
- publicDoublegetScore(){
- returnscore;
- }
- publicvoidsetScore(Doublescore){
- this.score=score;
- }
- }
- }
- publicList<partnerteamlist>getPartnerteamlist(){
- returnpartnerteamlist;
- }
- publicvoidsetPartnerteamlist(List<partnerteamlist>partnerteamlist){
- this.partnerteamlist=partnerteamlist;
- }
- }
- publicclasserr{
- privateintcode;
- privateStringmsg;
- publicintgetCode(){
- returncode;
- }
- publicvoidsetCode(intcode){
- this.code=code;
- }
- publicStringgetMsg(){
- returnmsg;
- }
- publicvoidsetMsg(Stringmsg){
- this.msg=msg;
- }
- }
- }
注意上面内部类的运用。
解析:
[java] view plain copy print ?- Gsongson=newGson();
- OtherDetaild=gson.fromJson(jsonString,Detail.class);//取值的时候就从父类一层一层调子类成员(重要)
更多相关文章
- Android(安卓)网络编程 Socket Http
- 蓝牙操作 Bluetooth
- android launcher总体分析 .
- Android_Intent意图详解
- Android之传感器(一)
- Android之解析Json数据 .
- android保存文件到sd卡,读取和清空记录功能(可以用来保存用户名和
- Android(安卓)布局转化为View对象的两种方法
- android 里面的 Drawable 和 ConstantState