问题解决:jmeter+java+beanshell : org.apache.jorphan.util.JMeterException: Error invoking bsh method: eva

使用fastJson来做json解析,出现报错。

Assertion failure message: org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval Sourced file: inline evaluation of: ``import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONArray; i . . . '' : Typed variable declaration : Method Invocation jsonObject.getJSONObject

原因如下:

要解析的json体是这样的:

{"code":0,"msg":"ok","data":{"open_id":"2c2d714c1b577332be3eac9784f98d1d"}}

  

代码如下:

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSON;

String resp=new String(ResponseData);
JSONObject jsonObject=JSON.parseObject(resp);
int code=jsonObject.getIntValue("code");
JSONObject data=jsonObject.getJSONObject("data");

String msg = jsonObject.getString("msg");

if((code==0)&&(msg.equals("ok"))&&(data.toString()!="")){
Failure=false;
}else if (code!=0){
Failure=true;
FailureMessage="code!=0";
}else if(!msg.equals("ok")){
Failure=true;
FailureMessage="msg!=ok";
}else{
Failure=true;
FailureMessage="data返回数据有误";
}

  

如果期望结果刚好格式和{"code":0,"msg":"ok","data":{"open_id":"2c2d714c1b577332be3eac9784f98d1d"}}一致,就不会报错。

如果期望结果格式不一致,就会报错。

比如json格式是这样的:

{"code":1001,"msg":"\u7b7e\u540d\u5931\u8d25","data":[]}

  

分析之后,得出 json体中,解析data时出现了错误。

在eclipse中调试代码,定位出错代码行:

JSONObject data=jsonObject.getJSONObject("data");

原因是,如果data里面没有[{xxxxxxx}],那data是个JSONArray,不是JSONObject;

eclipse会这么报错:

java.lang.ClassCastException: com.alibaba.fastjson.JSONArray cannot be cast to com.alibaba.fastjson.JSONObject

修改代码如下:

如果data是JSONObject对象,就赋值JSONObject,如果data是JSONArray,就赋值JSONArray

把错误代码行

 JSONObject data=jsonObject.getJSONObject("data");

  

替换为:

Object data = "";
if(jsonObject.containsKey("data")){
Object dataObject=jsonObject.get("data");
if(dataObject instanceof JSONObject){
data= jsonObject.getJSONObject("data");
}else if(dataObject instanceof JSONArray){
data=jsonObject.getJSONArray("data");
}
}else{
Failure=true;
FailureMessage="返回结果中没有data数据";
}