注意:在Androidstudio的App下build.gradle中添加Gson依赖
compile 'com.google.code.gson:gson:2.8.2'
一、中括号纯数组格式json:
[
{
"model": "123123",
"modelId": 131123456413,
"name": "Eillot",
"platform": "biz",
"ptUid": 0,
"sellUid": 0,
"status": 1,
"uid": 23,
"updatedAt": 1534148140000
},
{
"model": "12356456",
"modelId": 132112121,
"name": "Eillot",
"platform": "biz",
"ptUid": 0,
"sellUid": 0,
"status": 1,
"uid": 23,
"updatedAt": 1534314461000
}
]
1、解析过程:
1)使用JsonParser类把json的string转换成一个JsonArray对象
JsonArray jsonArray = new JsonParser().parse(json).getAsJsonArray();
2)使用增强时for循环
for(JsonElement data: jsonArray){
MainBean bean=new Gson().fromJson(data,MainBean.class);
//存放对象的list集合
list.add(bean);
}
二、最外侧大括号类型数组json
{
"ptNo": [
"PTNO-201806051648ry",
"PTNO-201806051723oo"
]
}
//先转JsonObject
JsonObject jsonObject = new JsonParser().parse(message).getAsJsonObject();
//再转JsonArray 加上数据头
JsonArray jsonArray = jsonObject.getAsJsonArray("ptNo");
ArrayList<String> list= new ArrayList<>();
//循环遍历
for (JsonElement data : jsonArray) {
//通过反射得到数组的字符串对象
String ptNumber= new Gson().fromJson(data, new TypeToken<String>() {
}.getType());
list.add(ptNumber);
}
三、最外侧大括号包含数组,并且数组又有多个大括号json
json:{
"muser": [
{
"name": "zhangsan",
"age": "10",
"phone": "11111",
"email": "11111@11.com"
},
{
"name": "lisi",
"age": "20",
"phone": "22222",
"email": "22222@22.com"
},
...
]
}
-----------------------------------------------------------------------
解析方法
//先转JsonObject
JsonObject jsonObject = new JsonParser().parse(strByJson).getAsJsonObject();
//再转JsonArray 加上数据头
JsonArray jsonArray = jsonObject.getAsJsonArray("muser");
Gson gson = new Gson();
ArrayList<UserBean> userBeanList = new ArrayList<>();
//循环遍历
for (JsonElement user : jsonArray) {
//通过反射 得到UserBean.class
UserBean userBean = gson.fromJson(user, new TypeToken<UserBean>() {}.getType());
userBeanList.add(userBean);
}
mainLView.setAdapter(new UserAdapter(this, userBeanList));
四、大括号包含数组,数组中有包含数组,数组再包含多个对象(一般人不会这么干)
{
"result": [
[
{
"id": 1,
"title": "直属销售额",
"value": "0"
},
{
"id": 2,
"title": "直属销售奖金",
"value": "0"
},
{
"id": 3,
"title": "直属见习销售额",
"value": "0"
},
{
"id": 4,
"title": "直属见习销售奖金",
"value": "0"
},
{
"id": 5,
"title": "直接推荐会员",
"value": "0"
},
{
"id": 14,
"title": "直属见习销售排名",
"value": 0
}
]
]
}
//先转JsonObject
val jsonObject = JsonParser().parse(str).asJsonObject
//直接转换成bean对象
var bean1: GsonArrayBean1? = null
bean1 = Gson().fromJson(jsonObject, GsonArrayBean1::class.java)
//通过for循环只能一个一个的去取,不适合那种循环的赋值,只适合写死的 模块中动态的recyclerview
for (index in 1..bean1.result.size) {
when (index) {
in 1..bean1.result.size -> {
for (i in bean1.result[0]) {
list.add(i)
}
}
2 -> {
for (i in bean1.result[1]) {
list.add(i)
}
}
3 -> {
for (i in bean1.result[2]) {
list.add(i)
}
}
}
}