Gson解析Json
没什么好说的,贴源码上来吧
其中的GSON,GSON1,GSONARRAY,GSONARRAY2是通过Json转成Java实体类生成的,下面是网址..没想到会这么简单
http://www.bejson.com/
对了 需要下载Gson包,百度上有..
/ 第一种 普通Json对象
// {"c":0,"m":"120","d":"KJSYRMOVMSOEMB==-FNE"}
Gson gson = new Gson();
GSON person = gson.fromJson("{"c":0,"m":"120","d":"KJSYRMOVMSOEMB==-FNE"}", GSON.class);
Log.i("RedWolf", "这种解析方式真的是有点牛逼__" + person.toString() + "
");
/ 第二种 Json数组
// [{"name":"盖伦","sex":"男","r":"大宝剑"},{"name":"蛮王","sex":"男","r":"野蛮冲撞"}]
Type listType = new TypeToken<List<GSONARRAY>>() {
}.getType();
List<GSONARRAY> persons = gson.fromJson("[{"name":"盖伦","sex":"男","r":"大宝剑"},{"name":"蛮王","sex":"男","r":"野蛮冲撞"}]", listType);
for (GSONARRAY ga : persons) {
Log.i("RedWolf", "这种解析方式真的是有点牛逼__" + ga.toString());
}
// 第三种 貌似所有形式的 不外乎两种 一种是对象,一种是对象数组,只不过是麻烦的对象数组和简单的对象数组而已
// {"name":"盖伦","sex":"男","skill":[{"name":"审判","info":"无敌风火轮"},{"name":"德玛西亚正义","info":"大宝剑"}],"address":"德玛西亚"}
// 说到底不就是一个对象么?
GSON2 root = gson.fromJson("{"name":"盖伦","sex":"男","skill":[{"name":"审判","info":"无敌风火轮"},{"name":"德玛西亚正义","info":"大宝剑"}],"address":"德玛西亚"}", GSON2.class);
Log.i("RedWolf", "这种解析方式真的是有点牛逼__" + root.toString());
// 那么就没了 给个综合点的例子吧
// [{"name":"盖伦","sex":"男","skill":[{"name":"审判","info":{"mp":"不消耗","type":"AD伤害"}},{"name":"德玛西亚正义","info":{"mp":"不消耗","type":"魔法伤害,对大反派造成真实伤害"}}],"address":"德玛西亚"},{"name":"拉克丝","sex":"女","skill":[{"name":"光之束缚","info":{"mp":"消耗","type":"AP伤害"}},{"name":"透光奇点","info":{"mp":"消耗","type":"AP伤害"}}],"address":"德玛西亚"}]
// 也是一个数组 那就照数组的方式写呗
Type listType2 = new TypeToken<List<GSONARRAY2>>() {
}.getType();
List<GSONARRAY2> ga2 = gson.fromJson("[{"name":"盖伦","sex":"男","skill":[{"name":"审判","info":{"mp":"不消耗","type":"AD伤害"}},{"name":"德玛西亚正义","info":{"mp":"不消耗","type":"魔法伤害,对大反派造成真实伤害"}}],"address":"德玛西亚"},{"name":"拉克丝","sex":"女","skill":[{"name":"光之束缚","info":{"mp":"消耗","type":"AP伤害"}},{"name":"透光奇点","info":{"mp":"消耗","type":"AP伤害"}}],"address":"德玛西亚"}]", listType2);
for (GSONARRAY2 ga : ga2) {
Log.i("RedWolf", "这种解析方式真的是有点牛逼__" + ga.toString());
}