asysbang

标题: GSON详细解析 [打印本页]

作者: admin    时间: 2016-3-7 10:18
标题: GSON详细解析
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










欢迎光临 asysbang (http://asysbang.com/) Powered by Discuz! X2.5