I have written jsp code for generating json .But its not generating exact JsonArray. Its like
[{"item":"747"},,{"item":"1617"},]
instead of
[{"item":"747"},{"item":"1617"}].
below is the code
JSONObject obj = new JSONObject();
JSONArray ja = new JSONArray();
obj.put("item", "747");
ja.put(obj);
obj = new JSONObject();
obj.put("item", "1617");
ja.put(obj);
out.println(ja);
I have tested your code by using json-simple-1.1.1.jar, worked fine there is no extra , came in output. while testing your code eclipse given one error message like put() method is undefined for the type JSONArray, so i replaced put with add like:
JSONObject obj = new JSONObject();
JSONArray ja = new JSONArray();
obj.put("item", "747");
ja.add(obj);
obj = new JSONObject();
obj.put("item", "1617");
ja.add(obj);
out.println(ja);
Also see Gson
Related
I am trying to iterate through a value (that is a hashMap) of a JSONObject.
First I get a server response that is a String.
Then I turn it into a String! like this:
val responseString = response.serverResponse
Then I turn it into a JSONObject like this:
val jsonObj = JSONObject(responseString.toString()).get("data")
I do the second step because I only want to keep the LinkedHashMap shown in the picture attached.
But the second step returns type "Any" and then I cant iterate through the LinkedHashMap
JSONObject myjsonObject = new JSONObject();
Iterator keyvalues = jsonObject.keys();
while(keys.hasNext()) {String key = keyvalues.next();
if (myjsonObject.get(key) instanceof myjsonObject) {
}
}
Hoping you'd be able to assist me with this error - I am getting
An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll
at the time when Client.Execute is called, I've shared my code below:
Thanks in Advance!
var Client = new RestClient();
Client.BaseUrl = new Uri("http://dummyurl.com/");
Client.Authenticator = new RestSharp.Authenticators.HttpBasicAuthenticator("username", "password");
var eventlist = new List<string>();
var request = new RestRequest(Method.POST);
request.AddHeader("event", "application/json");
string jsonBody = #"{'xxxxx':'xxxx',
'xxxx':'Xxxxx'}";
JObject jsonObject = JObject.Parse(jsonBody);
request.AddBody(jsonObject);
IRestResponse response = Client.Execute(request); //<<<--Throws Stackoverflow exception
var content = JsonConvert.DeserializeObject(response.Content);
It blows up on serialising the JObject instance. You don't need to overload your code with repeated serialization and JSON parsing.
To pass a ready-made JSON as the request body, just use AddParamerter(contentType, jsonString, ParameterType.RequestBody);
Set the content type accordingly to application/json or whatever your server wants.
I'm trying to post data via API to InsightVM. I keep getting error 400 which means wrong format. I break it down, the problem is in hostnames part.
JSONObject json = new JSONObject();
JSONArray array = new JSONArray();
if (host_info.getDataType() == dataType.Web_Vulnerability && methodType == MethodType.Add_host_To_Site)
{
JSONObject json2 = new JSONObject();
json2.put("name",host_info.getHost_fqdn());
json2.put("source", "Splunk");
array.add(json2);
DateTimeFormatter dtf = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
json.put("date",OffsetDateTime.now().format(dtf) );
json.put("ip",host_info.getHost_ip());
json.put("os",host_info.getOperating_system());
json.put("hostNames",array); // problem is here
}
is the code above provide the same format as below:
{
"date": "2019-05-20",
"ip": "00.00.00.00",
"os":"Linux",
"hostNames":
[
{
"name": "corporate-workstation-1102DC.acme.com",
"source": "Splunk"
}
]
}
JSONArray implements Collection.
While JSONObject has an overloaded put() method,
which takes a Collection and wraps it in a JSONArray which might be causing the problem.
Can you try the following -
jsonObject.put("hostNames",(Object)array);
I have a JsonObject created using Google Gson.
JsonObject jsonObj = gson.fromJson(response1_json, JsonElement.class).getAsJsonObject();
Also i made some modification to existing jsonobj as below :
JsonObject newObject = new JsonObject();
newObject.addProperty("age", "50");
newObject.addProperty("name", "X");
jsonObj.get("data").getAsJsonArray().add(newObject);
Now, using rest assured, i need to send the post request with this jsonobject. I tried the following but it doesn't work and throws exception:
Response postResponse =
given()
.cookie(apiTestSessionID)
.header("Content-Type", "application/json")
.body(jsonObj.getAsString())
.when()
.post("/post/Config");
Please guide me on this.
Try below code to send Json to a Post request using Rest-assured
//Get jsonObject from response
JsonObject jsonObj = gson.fromJson(response1_json, JsonElement.class).getAsJsonObject();
//Create new jsonObject and add some properties
JsonObject newObject = new JsonObject();
newObject.addProperty("age", "50");
newObject.addProperty("name", "X");
//Get jsonarray from jsonObject
JsonArray jArr = jsonObj.get("data").getAsJsonArray();
//Add new Object to array
jArr.add(newObject);
//Update new array back to jsonObject
jsonObj.add("data", jArr);
Response postResponse =
given()
.cookie(apiTestSessionID)
.contentType("application/json")
.body(jsonObj.toString())
.when()
.post("/post/Config");
I have a JSON dictionary as follows:
JSONObject jsonColMap = "{\"key1\": \"value1\", \"key2\": \"value2\"}";
I want to loop this in JSP such that I can do a for each key in this dictionary, do something. I tried to do the following but I run into an error:
aWF = (JSONObject) jsonParser.parse(request.getParameter("data"));
Set<String> entries = jsonColMap.entrySet();
Iterator<String> iter = entries.iterator();
while(iter.hasNext())
{
String key = iter.next().toString();
if(aWF.containsKey(key))
{
//do something
}
}
But this throws an error
java.util.HashMap$EntrySet cannot be cast to java.util.HashMap
What am I doing wrong ?
EDIT: It complains at the line where entries is created and assigned