問題解決: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數據";
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM