I'm making many HTTP request with JSON Payload and I'm reading one file for every single request to get JSON Payload as below.
postPayload1 = val postPayload = ElFileBody("Test_case1.json")
val TC1 = feed(accountNumberFeeder1)
.exec(http(testCase1).post(appendPathToUrl).headers(common_header).body(postPayload).asJSON
.check(status.is(200)
)
But, it becomes so many JSON files inside my resources directory now. So can I merge all my JSON together in one file as below.
{"testCase1":{
"activationSource": "HH",
"accountStatus": null,
}
}
{"testCase2":{
"activationSource": "HH",
"accountStatus": null,
}
}
and access it with my keys "testCase1", "testCase2" etc ?
val postPayload = ElFileBody("Test_case.json")
From official Gatling Documentation, I found http://gatling.io/docs/2.2.1/session/feeder.html
JSON feeders
Some might want to use data in JSON format instead of CSV:
val jsonFileFeeder = jsonFile("foo.json")
val jsonUrlFeeder = jsonUrl("http://me.com/foo.json")
For example, the following JSON:
[
{
"id":19434,
"foo":1
},
{
"id":19435,
"foo":2
}
]
will be turned into:
record1: Map("id" -> 19434, "foo" -> 1)
record2: Map("id" -> 19435, "foo" -> 2)
Note that the root element has of course to be an array.
Related
I want to convert XML to JSON using either Java or Scala. Below is the working code, but here I am not able to see any identifier for XML attributes in Json to differentiate it with elements.
I need help to get XML attributes with identifier(#) in Json output.
Input XML :
<Test>
<AttrTest Code="199" Pro="Intel" Version="9.106">
<Info>FD2F</Info>
</AttrTest>
</Test>
Code :
import org.json.XML
def xmlToJson(xml: String) = {
var PRETTY_PRINT_INDENT_FACTOR = 4
try {
val xmlJSONObj = XML.toJSONObject(xml)
val jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR)
jsonPrettyPrintString
} catch {
case ex: Exception =>
println(ex.toString)
}
}
val xmlStr = "<Test>\n\t\t<AttrTest Code=\"199\" Pro=\"Intel\" Version=\"9.106\">\n\t\t<Info>FD2F</Info>\n</AttrTest>\n</Test>\n\t"
println(xmlToJson(xmlStr))
Output :
{"Test": {"AttrTest": {
"Version": 9.106,
"Pro": "Intel",
"Info": "FD2F",
"Code": 199
}}}
Expected Output :
{"Test": {"AttrTest": {
"#Version": 9.106,
"#Pro": "Intel",
"Info": "FD2F",
"#Code": 199
}}}
Please help.
I am afraid it is not possible with the library you are using. Here's from their docs:
Some information may be lost in this transformation because JSON is a data format and XML is a document format. XML uses elements, attributes, and content text, while JSON uses unordered collections of name/value pairs and arrays of values. JSON does not does not like to distinguish between elements and attributes.
You may try looking into other XML->JSON libraries or implement a pre-conversion step that would, say, append a "#" prefix to each node's attribute.
This is my C# webservice which generates a JSON String. The below code block is what im using for that.
List<Dictionary<String, Object>> lstdict = new List<Dictionary<String, Object>>();
...
...
...
Logic for connecting db and getting records in msqldat (data reader)
goes here.
...
...
while (msqldat.Read())
{
var detls = new Dictionary<string, object>();
for (int i = 0; i < msqldat.FieldCount; i++)
{
detls.Add(msqldat.GetName(i), msqldat.IsDBNull(i) ? null :
msqldat.GetValue(i));
lstdict.Add(detls);
}
}
JavaScriptSerializer jss = new JavaScriptSerializer();
String mret = jss.Serialize(lstdict);
The above webservice is called in a java code from android studio and it returns the below String.
{"GetDataResult":"[
{\"uname\":\"hkIUZIikXVTC5aNaSva8IQ==\",
\"passwd\":\"hkIUZIikXVTC5aNaSva8IQ==\",
\"validupto\":\"\\\/Date(1545330600000)\\\/\",
\"dept\":\"juubHSHgLr\/3JWnrZCh5LeeW5Q7lioWOZ1\/Tg+YRy\/o=\",
\"rid\":1},
{\"uname\":\"hkIUZIikXVTC5aNaSva8IQ==\",
\"passwd\":\"hkIUZIikXVTC5aNaSva8IQ==\",
\"validupto\":\"\\\/Date(1545330600000)\\\/\",
\"dept\":\"juubHSHgLr\/3JWnrZCh5LeeW5Q7lioWOZ1\/Tg+YRy\/o=\",
\"rid\":2}]"}
I am trying to get the values in android application by using this Java code :
JSONObject uiobj = new JSONObject(mret);
JSONArray arrUserinfo = uiobj.getJSONArray("GetDataResult");
arrUserinfo.getJSONObject(0).getString("uname"))
The code fails at the second line. I'm new to JSON. Not sure if the JSON generated from c# code is not right or java code for parsing is not right. Please advise further. Thank you in advance.
The above json is serialized you need to parse json and then extract the object from it.
See this json valid..
{
"GetDataResult": [{
"uname": "hkIUZIikXVTC5aNaSva8IQ==",
"passwd": "hkIUZIikXVTC5aNaSva8IQ==",
"validupto": "/Date(1545330600000)/",
"dept": "juubHSHgLr/3JWnrZCh5LeeW5Q7lioWOZ1/Tg+YRy/o=",
"rid": 1
},
{
"uname": "hkIUZIikXVTC5aNaSva8IQ==",
"passwd": "hkIUZIikXVTC5aNaSva8IQ==",
"validupto": "/Date(1545330600000)/",
"dept": "juubHSHgLr/3JWnrZCh5LeeW5Q7lioWOZ1/Tg+YRy/o=",
"rid": 2
}
]
}
To parse json in java see below post..
https://www.geeksforgeeks.org/parse-json-java/
Because of the project requirement, I have to use com.fasterxml.jackson.databind library to parse JSON data cannot use other JSON libraries available.
I am new to JSON parsing, so not sure if there are better options here?
I would like to know how can I update a string value in an Array node in the JSON file.
Following is a sample JSON. Please note this is not the entire file content, it's a simplified version.
{
"call": "SimpleAnswer",
"environment": "prod",
"question": {
"assertions": [
{
"assertionType": "regex",
"expectedString": "(.*)world cup(.*)"
}
],
"questionVariations": [
{
"questionList": [
"when is the next world cup"
]
}
]
}
}
Following is the code to read JSON into java object.
byte[] jsonData = Files.readAllBytes(Paths.get(PATH_TO_JSON));
JsonNode jsonNodeFromFile = mapper.readValue(jsonData, JsonNode.class);
To update a root level node value e.g. environment in the JSON file , I found following approach on some SO threads.
ObjectNode objectNode = (ObjectNode)jsonNodeFromFile;
objectNode.remove("environment");
objectNode.put("environment", "test");
jsonNodeFromFile = (JsonNode)objectNode;
FileWriter file = new FileWriter(PATH_TO_JSON);
file.write(jsonNodeFromFile.toString());
file.flush();
file.close();
QUESTION 1: Is this the only way to update a value in JSON file and is it the best way possible? I'm concerned on double casting and file I/O here.
QUESTION 2: I could not find a way to update the value for a nested Array node e.g. questionList. Update the question from when is the next world cup to when is the next soccer world cup
You can use ObjectMapper to parse that JSON, it is very easy to parse and update JSON using pojo class.
use link to convert your json to java class, just paste your json here n download class structure.
You can access or update nested json field by using . (dot) operator
ObjectMapper mapper = new ObjectMapper();
String jsonString="{\"call\":\"SimpleAnswer\",\"environment\":\"prod\",\"question\":{\"assertions\":[{\"assertionType\":\"regex\",\"expectedString\":\"(.*)world cup(.*)\"}],\"questionVariations\":[{\"questionList\":[\"when is the next world cup\"]}]}}";
TestClass sc=mapper.readValue(jsonString,TestClass.class);
// to update environment
sc.setEnvironment("new Environment");
System.out.println(sc);
//to update assertionType
Question que=sc.getQuestion();
List assertions=que.getAssertions();
for (int i = 0; i < assertions.size(); i++) {
Assertion ass= (Assertion) assertions.get(i);
ass.setAssertionType("New Type");
}
I'm using jQuery File-Upload plugin with Struts 2.
In my action I am populating the JSON object "results" and that's all I want my action to return.
But it is also including the plugin's file object as well which is an incomplete JSON and causing everything to break on my callbacks.
(Please note that if I don't populate my result object then it will return a valid JSON "file" object.
Is there any way I could avoid returning the "file" JSON response? I just want my action to return only "results"
{
"results": [
{
"ExcelPath": "/usr/test/test.xlsx",
"ExcelName": "test.xlsx",
"TestExcelStatus": "success"
}
]
}
{
"file": {
"absolute": true,
"absoluteFile": null,
"absolutePath": "\/usr\/local\/apache-tomcat-7.0.39\/temp"
},
"path": "\/usr\/local\/apache-tomcat-7.0.39\/temp\/up
My Action is as below:
org.json.JSONObject resp = new JSONObject();
JSONArray resultsArray = new JSONArray();
resp.put("results",resultsArray);
JSONObject result = new JSONObject();
result.put("TestExcelStatus", "success");
result.put("ExcelName", this.fileFileName);
result.put("ExcelPath", fileToCreate.getPath());
resultsArray.put(result);
servletResponse.reset();
servletResponse.setHeader("Content-Type","application/json; charset=UTF-8");
servletResponse.setHeader("CacheControl","no-cache");
servletResponse.setHeader("Pragma","no-cache");
servletResponse.setHeader("Expires","-1");
//resp.writeJSONString(out);
resp.write(servletResponse.getWriter());
I am expecting the below line to clear the existing JSON and only return my "results" JSON. But it is still returning every thing.
servletResponse.reset();
And the desired JSON response must be as below without a "file".
{
"results": [
{
"ExcelPath": "/usr/test/test.xlsx",
"ExcelName": "test.xlsx",
"TestExcelStatus": "success"
}
]
}
The Struts action is always returning a result code that is used by the action invocation to execute a result configured to this action. I suspect that result is of type json.
If the action returning json result then by default the root property is initialized to the action instance or a model if you are using model-driven action.
It means that all public properties of the root object will be serialized to JSON. You can control this process with annotations placed on the properties, or configure the result with parameters to include/exclude some properties from the result.
Actually you only need to configure the root parameter of the result to return an object that you serialize to JSON. But because you are writing to response directly you can change the result code returned by the action to NONE. This is used by the actions that don't return any result.
I have this javascript code :
$.ajax({
url: 'assignRenameRuleToAgency.do',
data: {agenciesId:agenciesId,ruleId: JSON.stringify ( ruleIDd ) },
success: function(response) {
toastr.success(response.message);
}
})
in the server side I did this :
String ruleId = request.getParameter("ruleId");
String[] agenciesId = request.getParameterValues("agenciesId");
ruleId was correct, but agenciesId was null.
Get JSON response from ajax call and then convert that json response to Java objects using below solutions.
Click here to know the working examples
It is a single String, not an array! You can change your structure to
agenciesId: [agenciesId]
then it will be an array.
I would however map the JSON message to a single POJO, for example by using Jackson.
If the parameter for ruleId can be received the way you describe the following should work:
String ruleId = request.getParameter("ruleId");
String agenciesId = request.getParameter("agenciesId");
I found the solution :
String[] myJsonData = request.getParameterValues("json[]");