In my jmeter response i have javascript and json as a mix response from that i have to fetch a JSON array which is items
Here is part of a huge response which i am getting
DE.APP.task.TaskGrid.getAssignmentData = function () {
return {"items":[]};
};
DE.APP.task.TaskGrid.getResourceData = function () {
return {"items":[{"STANDARDRATEFORMAT":"0.00","ASSIGNED_HRS":0,"RESOURCE_NAME":"#Buddhika ","COST":"0.00","PERCENTASSIGNED":"100.00","EMAIL":"Buddhika75#mspblank.com","AVAILABLEFROM":"10-May-2011","ALLOCATED_HRS":"1872.00","RESOURCE_ID":36197221,"AVAILABLETO":"31-Mar-2012","calendar":{"exceptions":{},"weekDayHours"
In this response i have to fetch the json array which is in getResourceData() and not any other items.
How can we do this with beanshell assrtion?
You can use apache StringUtils to cut the string using a left boundary and a right boundary. Your left boundary is clear "return {" but I am not sure about your right boundary (the string that follows your JSON payload). In the below example, I've used the ]} as the delimiter to cut your JSON payload. Use prev.getResponseDataAsString() to pull the response payload as a string.
import org.apache.commons.lang3.StringUtils;
import net.minidev.json.parser.JSONParser;
import net.minidev.json.JSONObject;
import net.minidev.json.JSONArray;
String sInputString = "return {\"items\":[{\"STANDARDRATEFORMAT\":\"0.00\",\"ASSIGNED_HRS\":0,\"RESOURCE_NAME\":\"#Buddhika \",\"COST\":\"0.00\",\"PERCENTASSIGNED\":\"100.00\",\"EMAIL\":\"Buddhika75#mspblank.com\",\"AVAILABLEFROM\":\"10-May-2011\",\"ALLOCATED_HRS\":\"1872.00\",\"RESOURCE_ID\":36197221,\"AVAILABLETO\":\"31-Mar-2012\",\"calendar\":{\"exceptions\":{},\"weekDayHours\":{}}}]}";
//String sInputString = prev.getResponseDataAsString();
try {
// Use StringUtils to cut the string between the two
String sCutString = StringUtils.substringBetween(sInputString, "return {\"items", "]}");
String sFinalString = "{\"items" + sCutString + "]}";
log.info("sFinalString=" + sFinalString);
// Use JSONParser to parse the JSON
JSONParser parser = new JSONParser(JSONParser.ACCEPT_NON_QUOTE|JSONParser.ACCEPT_SIMPLE_QUOTE);
JSONObject rootObject = (JSONObject) parser.parse(sFinalString);
//JSONObject rootObject = (JSONObject) parser.parse(prev.getResponseDataAsString());
JSONArray jResourceArray = (JSONArray) rootObject.get("items");
for (int i=0; i < jResourceArray.size(); i++) {
log.info(jResourceArray.get(i).toString());
// You can access individual elements using this
log.info("RESOURCE_ID=" + jResourceArray.get(i).get("RESOURCE_ID"));
}
}
catch ( Exception ex) {
log.info("Exception.." + ex);
}
You can extract any part of the response using Regular Expressions. As action is need to perform on the response of particular request[sampler], you should use Post-Processors as child of that particular request. So basically use Regular Expression Extractor.
Assuming that your response is like this---
I have completed array of JSON object and added some tell which may be there. This is assumption that I'm making. Please check your actual response.
DE.APP.task.TaskGrid.getAssignmentData = function () {
return {"items":[]};
};
DE.APP.task.TaskGrid.getResourceData = function () {
return {"items":[{"STANDARDRATEFORMAT":"0.00","ASSIGNED_HRS":0,"RESOURCE_NAME":"#Buddhika ","COST":"0.00","PERCENTASSIGNED":"100.00","EMAIL":"Buddhika75#mspblank.com","AVAILABLEFROM":"10-May-2011","ALLOCATED_HRS":"1872.00","RESOURCE_ID":36197221,"AVAILABLETO":"31-Mar-2012","calendar":{"exceptions":{},"weekDayHours":{}}}]}
AnotherBlockthatYouCanIDenity
So you can have Post-Processor like this-
Please note that this RE may not be correct as i'm not sure about the response you are getting. Please check your response. You can test your regular expression in View Results Tree listener also.
Related
So I am requesting an API call to search records by phone number. If the response is unsuccessful, I want to change the URL to search the record by name. In order to send the request and obtain the response we have a try catch clause. My only thought would be to repeat the request and response using a new URL inside the original catch clause . Can anyone inform me how I should go about changing the URL and making a new request if the original request catches an exception. Here is my snippet of code that requests to search by phone number. And the stackstrace which is evident because the request fails.
OkHttpClient client = new OkHttpClient().newBuilder().build();
String phone = DNC_List[i].getNumber();
Request request = new Request.Builder().url("https://www.zohoapis.com/crm/v2/Leads/search?phone=" + phone)
.method("GET", null).addHeader("Authorization", "Zoho-oauthtoken 1000.xxxxxxxxxxxxxxxx.xxxxxxxxxxxxx")
.addHeader("Content-Type", "application/json")
.addHeader("Cookie",
"1a9a93sda653=12a340a9c5d3e8sfd2161d0b; crmcsr=43sdv9-07ads5-4549-a166-0aad54gw6b; _zcsr_tmp=435e5334fa5-4549-a1667s889s8cf6b; JSESSIONID=54FF23B98378EBB45E4FA411823B5E61")
.build();
System.out.println("request = " + request);
try {
Response response = client.newCall(request).execute();
String responseBody = response.body().string();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser parser = new JsonParser();
JsonElement je = parser.parse(responseBody);
String prettyJsonString = gson.toJson(je);
JSONObject json = new JSONObject(prettyJsonString);
System.out.println(i + "PrettyJson = " + prettyJsonString + "\n______________end of string________");
JSONArray jsonArray = (JSONArray) json.get("data");
JSONObject data0 = (JSONObject) jsonArray.get(0);
JSONObject owner = (JSONObject) data0.get("Owner");
String id = owner.getString("id");
String id2 = data0.getString("id");
DNC_ID[i] = id2;
System.out.println("DNC_ID[" + i + "]= " + DNC_ID[i]);
} catch (Exception e) {
// Need to search leads by name if phone number does not work
// How to change the URL to search by name
System.out.println("Entered catch clause: index = " + i);
e.printStackTrace();
}
Output for the failed code:
request = Request{method=GET, url=https://www.zohoapis.com/crm/v2/Leads/search?phone=1234567890, tags={}}
Entered catch clause: index = 0
org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
at org.json.JSONTokener.syntaxError(JSONTokener.java:507)
at org.json.JSONObject.<init>(JSONObject.java:222)
at org.json.JSONObject.<init>(JSONObject.java:406)
at com.App.main(App.java:103)
Your code is failing to parse some JSON it doesn't appear like it's necessarily because the search returned zero results. If that were true it would return an empty array. Double check your JSON shapes and make sure they match what the API returns.
Also, it appears like you are mixing and matching two different JSON libraries. The built in Android objects such as JSONObject and Google's GSON pick one and stick with one don't mix and match them.
To aid in debugging this use OkHttps built in logging system and experiment with setting different logger levels.
Also to help debug you can set up OkHttp debug logging with an interceptor.
Logger logger = LoggerFactory.getLogger(HttpUtil.class);
HttpLoggingInterceptor logging =
new HttpLoggingInterceptor((msg) -> {
logger.debug(msg);
});
logging.setLevel(Level.BODY);
client.addNetworkInterceptor(logging);
I have tried with gson and Jackson parsers unfortunately I couldn't achieve what I wanted to.
{
"rateName": "My Special Rate",
"adjustments": [
{
"adjustmentType": "LOAN_AMOUNT_GREATER_THAN_550K",
"rate": 0.75
},
{
"adjustmentType": "AMORTIZATION_TERM_LESS_THAN_30_YEARS",
"rate": -0.2
}
],
"errorTypes": [],
"premiumTaxs": [],
"renewalPremiums": [],
"totalInitialRate": 1.95,
"optimumPricing": false,
"miPricingVO": null,
"rateCardId": "BALS_NR",
"ratingInfoBaseRate": 1.4
}
Above is the Json I want to parse. I want to create generic methods using which I can access a value by name easily. For example:
getName(rateName) - Should return 'My Special Rate'
getNameFromArray(adjustmentType, adjustments) - Should return
'LOAN_AMOUNT_GREATER_THAN_550K'
Is there a way to do this? It should be generic so that this can be applied on any Json file.
Additional info: I tried using Gson, but this parses the whole file and throws an error if it finds an array.
JsonReader j = new JsonReader(new FileReader("Path of Json"));
j.beginObject();
while (j.hasNext()) {
String name = j.nextName();
if (name.equals("rateName")) {
System.out.println(j.nextString());
}
System.out.println(name);
}
I tried with jackson and encountered the same as Gson.
JsonFactory jfactory = new JsonFactory();
JsonParser jParser = jfactory.createJsonParser("Path of Json");
while (jParser.nextToken() != JsonToken.END_OBJECT) {
System.out.println(jParser.getCurrentName());;
}
If you mean standard library when you say generic, then org.json would be that library.
Altough not as intuitive as GSON or Jackson, it is easy to use it:
JSONObject jsonData = new JSONObject(jsonString);
String rateName= jsonData.getString("rateName");//My Special Rate
To parse array you need to loop:
JSONArray adjustments = jsonData.getJSONArray("adjustments");
for(int i = 0; i < adjustments.length(); i++){
JSONObject adjustment = adjustments.getJSONObject(i);
String adjustmentType = adjustment.getString("adjustmentType");
}
Hi You can use JASON READER , it readers the JSON and map the data into a MAP .
Below is the URL to Download the JAR JASON READER.
https://drive.google.com/open?id=0BwyOcFBoJ5pueXdadFFMS2tjLVU
Below is the example -
package com;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import com.JasonReader;
public class Test {
public static void main(String[] args) {
String request ="{\"rateName\": \"My Special Rate\",\"adjustments\":[{\"adjustmentType\": \"LOAN_AMOUNT_GREATER_THAN_550K\",\"rate\": 0.75},{\"adjustmentType\": \"AMORTIZATION_TERM_LESS_THAN_30_YEARS\",\"rate\": -0.2}],\"errorTypes\": [],\"premiumTaxs\": [],\"renewalPremiums\": [],\"totalInitialRate\": 1.95,\"optimumPricing\": false,\"miPricingVO\": null,\"rateCardId\": \"BALS_NR\",\"ratingInfoBaseRate\": 1.}";
//
Map<String,String> map =new HashMap<String,String>();
map=JasonReader.readJason(request,map);
//System.out.println(map);
for (Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey()+ "=" +entry.getValue());
}
}
}
OUTPUT -
rateCardId=BALS_NR
adjustments|rate1=-0.2
miPricingVO=null
adjustments|adjustmentType=LOAN_AMOUNT_GREATER_THAN_550K
adjustments|adjustmentType1=AMORTIZATION_TERM_LESS_THAN_30_YEARS
adjustments|rate=0.75
optimumPricing=false
totalInitialRate=1.95
rateName=My Special Rate
ratingInfoBaseRate=1.
You can use the standard JsonParser which is part of the javax.json package. This parser is part of Java EE since version 7 and you can use this parser without any additional library.
The parser allows you to navigate through a JSON structure using the so called 'pull parsing programming model'
JsonParser parser = Json.createParser(myJSON);
Event event = parser.next(); // START_OBJECT
event = parser.next(); // KEY_NAME
String key = parser.getString(); // 'rateName'
event = parser.next(); // STRING_VALUE
String value=parser.getString(); // 'My Special Rate'
event = parser.next(); // START_ARRAY
....
But of course you need to navigate through your json data structure
Or you can just use Jodd JSON parser. You just need to deserialize the input string and the result will be collected in regular Map and List.
JsonParser jsonParser = new JsonParser();
Map<String, Object> map = jsonParser.parse(input);
Simple as that - and the result is the most generic as it can be. Then just call map.get("rateName") to get your value and so on.
But notice that for adjustments you can get the way you want without some util method that would iterate elements and search for the right one. If you can, change the JSON so that you dont have an array of adjustments, but a map.
If you need specific results, just pass the type with the input string. See more about parsing features.
How can i parse an array with direct values , twice json encoded in Java, i get the data as a string and i want to get each value from the multidimensional array.
I'm kind of a noob regarding java, i managed to pull a not so elegant solution that encounters problems when i split by "," if the text inside has "," i could do it with regex but there must be a more elegant solution than this:
content = the data fetched from the api as a string
content = content.replace("\"[[", "[");
content = content.replace("]]\"", "]");
content = content.replaceAll("\\\\","");
for (String FaData : content.split("\\],\\[")) {
for (String FaDataData : FaData.split(",")) {
FaDataData.toString();
}
}
Here you have an example of how content string actually looks like when is fetched:
"[[308576,1410880665,162506,\"Bobcat\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308576.jpg\",\"Well no\",82,3,\"\"],[308592,1410883832,9479,\"undeathkiller\",2,\"http:\\\/\\\/hugelolcdn.com\\\/i\\\/308592.gif\",\"Guess the stupidity level\",89,9,\"\"],[308574,1410879991,32277,\"rady123lol\",2,\"http:\\\/\\\/hugelolcdn.com\\\/i\\\/308574.gif\",\"force of habit\",92,3,\"\"],[308624,1410897686,149704,\"Raptide7\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308624.jpg\",\"*breathing intensifies*\",114,8,\"\"],[308648,1410911037,114669,\"Huller\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308648.jpg\",\"SPOILERS: Stannis kills Dumbledore\",133,2,\"\"],[308628,1410898654,135315,\"Mig_L\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308628.jpg\",\"So badass\",117,2,\"gold\"],[308639,1410902872,62886,\"burningowl\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308639.jpg\",\"Kid's going places yo\",125,4,\"\"],[308520,1410858123,73400,\"koppie888\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308520.jpg\",\"4chan, what a beautifull place\",99,7,\"\"],[308546,1410872801,32277,\"rady123lol\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308546.jpg\",\"( \\u0361\\u00b0 \\u035c\\u0296 \\u0361\\u00b0)\",118,17,\"\"],[308486,1410846601,176339,\"AtLeastISubmit\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308486.jpg\",\"That 70's show called it.\",101,3,\"\"]]"
Assuming that you have your text in a String variable called everything, using the JSONSimple package, you can use the following code:
try {
// create a new JSONParser
JSONParser parser=new JSONParser();
// first JSON decoding
Object obj = parser.parse(everything);
// second JSON decoding
obj = parser.parse(obj.toString());
// cast the parsed JSON string to a new JSONArray
JSONArray array = (JSONArray)obj;
// loop through each line of the initial JSONArray
for (int i = 0; i < array.size(); i++){
// write the array values as a single line
System.out.println(i + " : " + array.get(i));
// parsing each line as a new JSONArray
JSONArray tmp = (JSONArray)parser.parse(array.get(i).toString());
for (int j = 0; j < tmp.size(); j++){ // iterate over the parsed values
System.out.println(i+"."+j+" : "+tmp.get(j));
}
}
} catch (ParseException ex) {
Logger.getLogger(Test1.class.getName()).log(Level.SEVERE, null, ex);
}
Of course, you also have to import the following classes from the JSON package :
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
Try this
content = content.trim();
content = content.substring(0, content.length()); //gets the length of content string
content = content.replaceAll("\\/","/"); //Replaces all \/ to /
It would apply to the brackets as well.
If you're using JSON then I would suggest using a JSON library such as jackson.
ObjectMapper mapper = new ObjectMapper();
String[][] 2Darray = mapper.readValue(content, String[][].class);
But then, if you are using JSON it would be nice if the format of your data was more structured. Obviously, that depends on whether or not you have any control over the API.
I am getting the data from the Zookeeper node like this
byte[] bytes = client.getData().forPath("/my/example/node1");
String ss = new String(bytes);
Here ss will have data like this which is a simple JSON String consisting of key value pair -
{"description":"Some Text", "machinename":"machineA", "ipaddress":"192.128.0.0"}
Now I want to append one more key value pair at the end to the above JSON String. This is the below key value pair I want to append -
"version":"v3"
So the final JSON String will look like this -
{"description":"Some Text", "machinename":"machineA", "ipaddress":"192.128.0.0", "version":"v3"}
What's the best and efficient way to do this?
Use a JSON Parser/Generator to parse your given JSON to a tree structure and then add your JSON field.
With Gson, that would look something like this
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(ss, JsonObject.class); // parse
jsonObject.addProperty("version", "v3"); // modify
System.out.println(jsonObject); // generate
prints
{"description":"Some Text","machinename":"machineA","ipaddress":"192.128.0.0","version":"v3"}
Will Zookeeper always return valid JSON or their custom format? Be aware of that.
When it comes to JSON processing, string manipulation only works in special and simple cases. For the general case, a good JSON parser library should be used.
Jackson is among the top of such libraries in terms of performance, efficiency, versatility and reliability, plus it is published under the commercial-friendly Apache 2.0 license.
Following is a simple implementation of the requested answer in Jackson.
public static void main(String[] args)
{
String ss = "{\"description\":\"Some Text\", \"machinename\":\"machineA\", \"ipaddress\":\"192.128.0.0\"}";
System.out.println("JSON string before: " + ss);
try
{
ObjectMapper mapper = new ObjectMapper();
Map<String, String> map = (Map<String, String>)mapper.readValue(ss, Map.class);
map.put("version", "v3");
ss = mapper.writeValueAsString(map);
}
catch (Exception e)
{
e.printStackTrace();
}
System.out.println("JSON string after: " + ss);
}
Basic string manipulation. Insert your additional string before the final close brace }. Make sure to add a comma.
Json objects don't need to be ordered.
String json = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
String json2 = "\"version\":\"v3\"";
json2 = ',' + json2;
String json3 = json.substring(0,json.length()-1) + json2 + json.charAt(json.length()-1);
That should be the simplest, most efficient way, if that's all you need to do.
For additional reading on String manipulation,
http://docs.oracle.com/javase/tutorial/java/data/manipstrings.html
Very New with Java Development Parsing JSON in JAVA Here is my Code.
package com.zenga.control;
import java.io.BufferedReader;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
public class Start {
public String readUrl(String urlString) {
String jsonString = null;
try {
HttpClient client = new HttpClient();
GetMethod get = new GetMethod(urlString);
client.executeMethod(get);
jsonString = get.getResponseBodyAsString();
}catch(Exception e) {
}
return jsonString;
}
public void getAddAsBeanObject() {
try {
String jsonString = new Start().readUrl("http://myDomain/JsonZ.json");
JSONObject obj = (JSONObject) JSONSerializer.toJSON(jsonString);
System.out.println(obj);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new Start().getAddAsBeanObject();
}
}
As I successfully Read Value in JSONObject and it also showing all JSON String on console But How can i Get Value For ID and UID and DURATION ?
Here The JSONString the i read in System.out.println(obj);
{
"Demo": {
"CONTENT": [
{
"ID": " 283 ",
"UID": " 87897bc8-ae9b-11e1-bdcf-123141042154 ",
"DURATION": "Full"
},
{
"ID": " 283 ",
"UID": " 87897bc8-ae9b-11e1-bdcf-123141042154 ",
"DURATION": "Full"
}
]
}
}
Following code can be used to iterate the JSON objects inside the JSON array 'CONTENT', using .get(java.lang.String) as documented, to pull the value out of the JSONObject.
I have only demonstrated how to get the ID but the same logic applies to the other values.
JSONObject obj = (JSONObject) JSONSerializer.toJSON(jsonString);
JSONArray content = obj.getJSONObject("Demo").getJSONArray("CONTENT");
java.util.Iterator<?> iterator = content.iterator();
while (iterator.hasNext()) {
JSONObject o = (JSONObject) iterator.next();
System.out.println(o);
System.out.println(o.get("ID"));
// etc...
}
Following is a sample code to reach the array`s inner objects specific to pattern you have provided.
String str = "{"+
"\"Demo\": {"+
"\"CONTENT\": ["+
" {"+
"\"ID\": \" 283 \","+
"\"UID\": \" 87897bc8-ae9b-11e1-bdcf-123141042154 \","+
"\"DURATION\": \"Full\""+
" },"+
"{"+
"\"ID\": \" 283 \","+
"\"UID\": \" 87897bc8-ae9b-11e1-bdcf-123141042154 \","+
"\"DURATION\": \"Full\""+
" }"+
"]"+
"}"+
"}";
try {
JSONObject jsr = new JSONObject(str); // JSON object with above data
JSONObject demo = jsr.getJSONObject("Demo"); // get Demo which is a JSON object inside jsr.
JSONArray content = demo.getJSONArray("CONTENT");// get CONTENT which is Json array inside Demo
for (int i = 0; i < content.length(); i++) { // iterate over array to get inner JSON objects and extract values inside
JSONObject record = content.getJSONObject(i); // each item of Array is a JSON object
String ID = record.getString("ID");
String UID = record.getString("UID");
String DURATION = record.getString("DURATION");
}
}
catch (JSONException e) {
e.printStackTrace();
}
Note: Above code is specifc to org.Json API. Find appropriate methods in library you are using for Json handling
Use a loop that iterates through the Json Object and access each of the element
for(/**loop until the counter reaches the size of the json object**/) {
//Access each element based on the ID as below.
System.out.println(Demo.CONTENT[CurrentCounter].ID); //here CurrentCounter is index
System.out.println(Demo.CONTENT[CurrentCounter].UID); ..... //read through all ids
}
I guess you could use the 'get' Method on the JSONObject. If you don't know which key to look for, I suggest using a Method that returns all available keys, like the one called 'keys'. With these values, you could then traverse down in you structure. See here:
http://json-lib.sourceforge.net/apidocs/net/sf/json/JSONObject.html
I guess GSON will be a big help for you.
See here Parsing json object into a string
There is a samplecode as well
Create a class which have variables you want to read from json string.And Gson will handle the rest.
https://code.google.com/p/google-gson/
Example usage:
//convert the json string back to object
DataObject obj = gson.fromJson(br, DataObject.class);