问题
This is my json i want to extract firstname and code using beanshell script.But i'm not able to extract the values . Please help
{
"code":"HNYC",
"message":"Sucess",
"data":{
"Employeid":"TGRDH-887",
"Perosonal":{
"Details":{
"firstname":"Sam",
"id":3566,
"dob":"23/11/1990",
"Yearofjoing":"2018",
"Salary":30000,
"Address":"New Delhi",
"City":"Delhi"
}
}
}
}
Beanshell Code:
import com.eclipsesource.json.JsonObject;
String jsonString = prev.getResponseDataAsString();
JsonObject accountId = JsonObject.readFrom(jsonString);
String code = accountId.getJSONObject("code");
print("value "+code);
回答1:
First of all, do you know about JSON Extractor? If not - consider using it as it provides possibility to fetch JSON data using simple JSONPath queries like $..code
and $.. firstname
If you still want to go for scripting be aware that since JMeter 3.1 it is recommended to use Groovy for any form of scripting. Groovy is more "modern" language than Beanshell, it supports all new Java features and it has a lot of enhancements on top of Java SDK
One of them is built-in JSON support via JsonSlurper class, so you can shorten your code to something like:
def json = new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())
String code = json.code
log.info(code)
Demo:
More information:
- Groovy: Parsing and producing JSON
- Apache Groovy - Why and How You Should Use It
回答2:
You can get code
value directly from JSONObject, since it is property in JSONObject refer
String code = accountId.get("code");
回答3:
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject getData = jsonObject.getJSONObject("data");
JSONObject getPerosonal = getData.getJSONObject("Perosonal");
JSONObject getDetails = getPerosonal.getJSONObject("Details");
Object firstname= getDetails.get("firstname");
System.out.println(firstname);
来源:https://stackoverflow.com/questions/53220485/extract-json-values-in-beanshell-script