asysbang

 找回密码
 立即注册
查看: 4341|回复: 0
打印 上一主题 下一主题

GSON详细解析

[复制链接]

513

主题

2

好友

6404

积分

管理员

Rank: 80Rank: 80Rank: 80Rank: 80Rank: 80

最佳新人 活跃会员 热心会员 推广达人 宣传达人 灌水之王 突出贡献 优秀版主 荣誉管理 论坛元老

跳转到指定楼层
楼主
发表于 2016-3-7 10:18:29 |只看该作者 |倒序浏览
GSON项目源代码地址
https://github.com/google/gson

最新的jar下载地址(去下面网址搜索gson)
http://mvnrepository.com/


下载下来的目录结构
CHANGELOG.md  
examples  
gson                  
lib      
metrics  
proto      
ReleaseProcess.md
codegen      
extras   
GsonDesignDocument.md  
LICENSE  
pom.xml  
README.md  
UserGuide.md

#需求
gson是常用的框架

#分析
1.如何解析数组
```
[
  {
    "id": "1",
    "tag": "tag1",
    "tobe": "tobe1"
  },
  {
    "id": "2",
    "tag": "tag2",
    "tobe": "tobe2"
  }
]
```
```
Gson gson = new Gson();
Course[] courses = gson.fromJson(sg.toString(), Course[].class);
```
2.带数据头的数组数据
```
{
  "code":"1",
  "msg":"success",
  "data":[
    { "id": "1",
      "info": "1连",
      "parent_id":"0",
      "tobe": "tobe1"
    },
    { "id": "2",
      "info": "2连",
      "parent_id":"1",
      "tobe": "tobe1"
    },
    { "id": "3",
      "info": "3连",
      "parent_id":"2",
      "tobe": "tobe1"
    }
  ]
}

public class DataHead<T> {

    public int code;

    public String msg;

   @SerializedName(value = "datas",alternate = {"data","dataa"})
    public T[] datas;
}

Gson gson = new Gson();
Type unitType = new TypeToken<DataHead<Unit>>(){}.getType();
DataHead<Unit> head = gson.fromJson(str,unitType);
return head.datas;

```

3.jsonReader使用

4.遇到空字符串时如果转换类型会报错的

#过程

1





回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

Archiver|手机版|aSys-帮 ( 京ICP备13033689号 )

GMT+8, 2024-10-5 17:18 , Processed in 0.046880 second(s), 19 queries .

Powered by Discuz! X2.5

© 2001-2012 Comsenz Inc.

回顶部