一、Json示例
{
"resCode" : 0 ,
"msg" : "SUCCESS" ,
"firstJson" : {
"secondJson" : "sencondJson value" ,
"secondJson1" : [
{
"thirdJson" : 1234 ,
"thirdJson1" : [
{
"fourthJson" : [
{
"fifthJson" : true
}
]
}
] ,
"thirdJson2" : {
"fourthJsonList" : "fourthJson list value" ,
"fourthJsonList1" : "fourthJson list value1"
}
}
] ,
"secondJson2" : {
"thirdJsonList" : "thirdJson list value" ,
"thirdJsonList1" : "thirdJson list value1"
}
}
}
二、Java代碼
import com. alibaba. fastjson. JSONArray;
import com. alibaba. fastjson. JSONObject;
public class JsonUtil {
public static String getJsonValueRec ( String response, String keys, int index) {
String[ ] key = keys. split ( "\\." ) ;
if ( key. length == 1 ) {
if ( response. startsWith ( "[" ) ) {
return parseJsonArray ( response, index, key[ 0 ] ) ;
}
if ( response. startsWith ( "{" ) ) {
return parseJsonObject ( response, key[ 0 ] ) ;
}
} else if ( key. length > 1 ) {
if ( response. startsWith ( "[" ) ) {
response = parseJsonArray ( response, index, key[ 0 ] ) ;
keys = keys. substring ( key[ 0 ] . length ( ) + 1 ) ;
return getJsonValueRec ( response, keys, index) ;
}
if ( response. startsWith ( "{" ) ) {
response = parseJsonObject ( response, key[ 0 ] ) ;
keys = keys. substring ( key[ 0 ] . length ( ) + 1 ) ;
return getJsonValueRec ( response, keys, index) ;
}
}
return "No corresponding value found" ;
}
private static String parseJsonArray ( String response, int index, String key) {
JSONArray resultArray = JSONObject. parseArray ( response) ;
return resultArray. getJSONObject ( index) . getString ( key) ;
}
private static String parseJsonObject ( String response, String key) {
JSONObject jsonObject = JSONObject. parseObject ( response) ;
return jsonObject. get ( key) . toString ( ) ;
}
}