Gson获取json字符串中key对应的值

字符串 :

//得到服务器返回的具体内容

1
final String res = response.body().string();

例1:{"code":100,"msg":"处理成功!","extend":{"jsonString":{"userId":1,"userName":"123","userPwd":"123"}}}

1
2
3
4
5
6
7
8
9
10
jsonObject = (JsonObject) new JsonParser().parse(res).getAsJsonObject();

// 获取  code:
jsonObject.get("code").getAsInt();

// 获取  userName:
jsonObject.get("extend")
.getAsJsonObject().get("jsonString")
.getAsJsonObject().get("userName")
.getAsString()

例2:{"code":100,"msg":"处理成功!","extend":{"jsonString":[{"userId":1,"userName":"123","userPwd":"123"}]}}

1
2
3
4
5
6
7
8
9
10
11
jsonObject = (JsonObject) new JsonParser().parse(res).getAsJsonObject();

// 获取  code:
String code = jsonObject.get("code").getAsInt();

// 获取  userName:
String userName = jsonObject.get("extend")
.getAsJsonObject().get("jsonString")
.getAsJsonArray().get(0)
.getAsJsonObject().get("userName")
.getAsString()