【转】Android Gson的使用

Android Gson

目前的客户端大都有和服务端进行交互,而数据的格式基本就是json了,因而在Android开发中就常常用到json解析,方便的是Google已经为咱们提供了一个很棒的json解析库–gson,那么今天就来总结分享下gson的各类用法。html

gson的官方下载地址:google-gsonjava

单个对象

首先咱们来看一个最简单的用法,假设json的数据格式是这样的:android

{ "id": 100, "body": "It is my post", "number": 0.13, "created_at": "2014-05-22 19:12:38" } 

那么咱们只须要定义对应的一个类:git

public class Foo { public int id; public String body; public float number; public String created_at; } 

使用起来只需以下几行代码就好了:github

public static final String JSON_DATA = "..."; Foo foo = new Gson().fromJson(JSON, Foo.class); 

这里是最简单的用法,created_at直接定义了String类型,若是你想要Date类型的也能够,就变成下面的例子:编程

public class Foo { public int id; public String body; public float number; public Date created_at; } public static final String JSON_DATA = "..."; GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.setDateFormat("yyyy-MM-dd HH:mm:ss"); Gson gson = gsonBuilder.create(); Foo foo = gson.fromJson(JSON_DATA, Foo.class); 

有人说created_at不是java风格,java编程规范是驼峰结构,那么ok,Gson很人性化的也提供注解的方式,只须要把Foo对象改为这样就ok了:json

public class Foo { public int id; public String body; public float number; @SerializedName("created_at") public String createdAt; } 

而后用法不变,是否是很方便。数组

对象的嵌套

假设要返回以下数据:ruby

{ "id": 100, "body": "It is my post", "number": 0.13, "created_at": "2014-05-22 19:12:38" "foo2": { "id": 200, "name": "haha" } } 

那么对象的定义是这样的post

public class Foo { public int id; public String body; public float number; public String created_at; public ChildFoo foo2; public class ChildFoo { public int id; public String name; } } 

对象数组

假如返回的是json数组,以下:

[{ "id": 100, "body": "It is my post1", "number": 0.13, "created_at": "2014-05-20 19:12:38" }, { "id": 101, "body": "It is my post2", "number": 0.14, "created_at": "2014-05-22 19:12:38" }] 

这种解析有两种方法:

  • 一、解析成数组
public static final String JSON_DATA = "..."; Foo[] foos = new Gson().fromJson(JSON_DATA, Foo[].class); // 这时候想转成List的话调用以下方法 // List<Foo> foosList = Arrays.asList(foos); 
  • 二、解析成List
public static final String JSON_DATA = "..."; Type listType = new TypeToken<ArrayList<Foo>>(){}.getType(); ArrayList<Foo> foos = new Gson().fromJson(JSON_DATA, listType); 

总结

上面基本就总结到开发中经常使用到的集中类型,用法很简单方便,主要须要json数据抽象成对应的数据模型就ok了。不过阿里也有一套本身的开源json解析库–FastJson,听说性能更佳,可是实际应用中感受Gson的解析已经至关快了,并且更习惯用Google官方的东西,因此对FastJson没有怎么研究,之后有时间使用体验一下。

相关文章
相关标签/搜索