最近在学习过程中使用到了使用Gson解析Json数据,解析过程中我们遇到的最大问题就是JavaBean的建立,一旦建立好了JavaBean,后面获取数据的过程也就事半功倍了。
下面是我在学习使用该方法的思路:1 首先看这段较为简单的Json数据:
{
"a":"10",
"b":[{"b1":"1","b2":"2"},{"b1":"3","b2":"4"} ],
"c":{"c1":"10","c2":"20"}}
我们知道,当我们使用jsonObject和JsonArray解析Json数据时"a":"10" 我们可以直接获取;[ ]我们可以当成JsonArray数组;{ }我们可以当成jsonObject对象,在Gson中创建JavaBean时是同样的思路
以下创建相对应的javaBean :
public class Data{
public String a;
public List<B> b;
public C c;
public static class B{
public String b1;
public String b2;
}
public static class C{
public String c1;
public String c2;
}
}
这里的变量名,对象名,都必须和你的Json数据里面的键保持一致,
Gson gson = new Gson();
Type type = new TypeToken<Data>(){}.getType();
Data data = gson.fromJson(result, type);
然后数据都在data里面了,取出来就可以了。
2 若碰到以下的Json数据:
{"users":
{
"code":"1001",
"name":"JOHN",
"kb":[
{"detail":{"t1":"SQL","t2":"C语言","t3":"","t4":""},"weekday":"星期一"},
{"detail":{"t1":"Java","t2":"J2EE","t3":"C","t4":""},"weekday":"星期二"},
{"detail":{"t1":"AA","t2":"BB","t3":"DD","t4":""},"weekday":"星期三"},
{"detail":{"t1":"AA","t2":"","t3":"","t4":""},"weekday":"星期四"},
{"detail":{"t1":"","t2":"BB","t3":"","t4":"EE"},"weekday":"星期五"}
]
}
}
思路也大致一样,在使用内部类嵌套时,一定要给该内部类加上static
相对应的javaBean :
public class Data {
public Users users;
public static class Users{
public String code;
public String name;
public List<KB> kb;
public static class KB{
public Detail detail;
public String weekday;
public static class Detail{
public String t1;
public String t2;
public String t3;
public String t4;
@Override
public String toString() {
return "Detail [t1=" + t1 + ", t2=" + t2 + ", t3=" + t3
+ ", t4=" + t4 + "]";
}
}
}
}
}
调用以下代码:
Gson gson = new Gson();
Type type = new TypeToken<Data>(){}.getType();
Data data = gson.fromJson(result, type);
Users users = data.users;
String code = users.code;
String name = users.name;
Log.i("MainActivity", "code:" + code + ";name: " + name);
List<KB> kb = users.kb;
for (KB k: kb) {
String weekday = k.weekday;
Log.i("MainActivity", "weekday: "+ weekday);
Detail detail = k.detail;
Log.i("MainActivity", detail.toString());
}
这样就能获取到我们想要 的数据了,我这里只是两个复杂一点点的数据,还有更为复杂的思想大致也跟这个一样。在下面的文件中,我把相应的Gson框架传上去了,使用时需要导入gson-2.3.1.jar这个jar包,关联源码请看我的上篇文章
安卓导入源码