GSON - JsonParser对响应数据解析的封装
JsonUtil.java
一.解析一层json树结构
{
"username":"YWRtaW4=",
"password":"bGlhblNoaTIwMjA="
}
调用:gsonParserString(jsonstr,"username");
/**
* 解析一层json树结构,只有JsonObject,获取第1层json中某个key的值
* @param jsonString
* @param dataKey()
* @throws RuntimeException
*/
public static String gsonParserString(String jsonString,String dataKey){
//生成gson对象
Gson gson = new Gson();
//把json转换成JsonObject对象
JsonObject contenJson = gson.fromJson(jsonString, JsonObject.class);
String value=contenJson.get(dataKey).getAsString();
return value;
}
二、解析二层json树结构
{
"code": 0,
"data": {
"accessToken": "eyJhbGciOiJIUzUxMiJ9",
"expiresIn": 600
}
}
调用:gsonParserString_2(jsonStr,"accessToken");
/**
* 解析二层json树结构,只有JsonObject,获取第2层json中某个key的值
* @param jsonString
* @param dataKey()
* @throws RuntimeException
*/
public static String gsonParserString_2(String jsonString,String dataKey){
//生成gson对象
Gson gson = new Gson();
//把json转换成JsonObject对象
JsonObject contenJson = gson.fromJson(jsonString, JsonObject.class);
//value为int时,取出int
//int code = jsonObject.get("code").getAsInt();
//System.out.println("code: "+code);
JsonObject datajson=contenJson.get("data").getAsJsonObject();
if (contenJson.get("code").getAsInt() == 0){
//value为JsonObject时,取出JsonObject,再获取String
String value=datajson.get(dataKey).getAsString();
//System.out.println(value);
return value;
}
else {
throw new RuntimeException("获取信息失败:" + contenJson.get("code"));
}
}
三、解析三层json树结构
{
"code": 0,
"data": {
"totalCount": 1,
"pageSize": 10,
"totalPage": 1,
"currPage": 1,
"list": [
{
"nosqlConnectionId": "1437248934484402178",
"connectionName": "mongotest",
"dataBaseType": "mongo",
"proxyPort": null,
"dataBaseName"