jmeter beanshell遍历接口返回的json数组

时间:2021-09-22 07:43:34
import java.util.LinkedHashMap;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Predicate;
import net.minidev.json.JSONArray;

public static String readjson( String json, String jsonPath )
{
    try{
        Object value = JsonPath.read( json, jsonPath, new Predicate[0] );
        if ( value instanceof Integer )
        {
            return(value.toString() );
        }else if ( value instanceof String )
        {
            return(value.toString() );
        }else if ( value instanceof Boolean )
        {
            return(value.toString() );
        }else if ( value instanceof JSONArray )
        {
            JSONArray arr = (JSONArray) value;
            if ( !arr.isEmpty() )
            {
                return(arr.toJSONString() );
            }else
                return("");
        }else if ( value instanceof LinkedHashMap )
        {
            return(value.toString() );
        }else if ( value instanceof Float )
        {
            return(value.toString() );
        }else{
            return(value.toString() );
        }
    }catch ( Exception e ) {
        return("pathnotfound");
    }
}

String rep, jsonPath, result;
rep    = prev.getResponseDataAsString();
jsonPath = "$.data.lists.length()";
result = readjson( rep, jsonPath );
int length = Integer.valueOf(result).intValue();
ArrayList    agent_versionArry = new ArrayList();
for ( int i = 0; i < length; i++ )
{
    jsonPath = "$.data.lists[" + i + "].badge";
    result = readjson( rep, jsonPath );
    agent_versionArry.add( result );
    print( agent_versionArry );
}