creating json as is shown in Postman - json

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);

Related

serialize a json using gson

I am using com.google.gson.JsonObject to send the json inside 'parameters' to a rest endpoint.
{
"parameters":
"{
\"customer\" : {
\"firstName\": \"Temp\",
\"lastName\": \"Temp\",
\"emailAddresses\": [\"temp1#temp.com\"],
\"address\": {
\"street1\": \"123 W Temp St\",
\"city\": \"Temp\",
\"state\": \"Illinois\",
\"zipCode\": \"61122\"
}
},
\"options\" : [\"tv\"]
}"
}
Since Parameters is a json string, I am trying to do this :
JsonObject json = new JsonObject();
json.addProperty("options", ??);
I am not sure how to do it for customer and options.
'options' is a java Set, whereas customer is an object.
You may use:
Gson gson = new Gson();
String json = "{\"parameters\": {\"customer\" ... ";
JsonObject jsonObject = gson.fromJson(json, JsonObject.class);
JsonArray options = new JsonArray();
options.add("tv");
jsonObject.add("options", options);
String output = gson.toJson(jsonObject);

Iterate through JSONObject

I am working on writing a groovy script now and I am absolute new in groovy lang.
I have Json Object, like that:
{
"firstVar": {
"active": "false",
"title": "First Var"
},
"secondVar": {
"active": "false",
"title": "Second Var"
}
}
I need to iterate over this Json object. Count of items in this object may be various, like "sixthVar". I know solution in Java, and need something similar in groovy:
JSONObject jsonObject = new JSONObject(contents.trim());
Iterator<String> keys = jsonObject.keys();
while(keys.hasNext()) {
String key = keys.next();
if (jsonObject.get(key) instanceof JSONObject) {
// do something with jsonObject here
}
}
Or maybe there are some way to convert Json object to Json array?
I found the solution by trial and error. There is way of iteration like in Json Array:
jsonObject.each {
// do something with it.key and it.value pair
}

I'm trying to convert my Json Object to pretty format using gson but encountering something odd

JsonObjectBuilder builder = factory.createObjectBuilder().add("input", input);
JsonObject jsonData = builder.build();
String jsonDataString = jsonData.toString();
try {
OutputStream jsonStream = new FileOutputStream(jsonPath);
OutputStreamWriter jsonStreamWriter = new OutputStreamWriter(jsonStream);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String prettyOutput = gson.toJson(jsonData);
System.out.println(prettyOutput);
jsonStreamWriter.write(prettyOutput);
}
catch(Exception e) {}
The output I get is weird:
It adds '"value":' before every string value of a key.
My JSON data is something like this:
{
"input": {
"record0": {
"Active": "",
"Level": "",
"Name": "Pre-Session",
"Description": "",
"Record": "",
"Field": "",
"Std. Rule": "",
"Ext. Rule": "//Updated By: Sukanya Dasgupta On: 25-Jan-2016"
}
}
}
Not an expect but I think the problem is that public String toJson(Object src) loses type information :
This method should be used when the specified object is not a generic
type. This method uses Object.getClass() to get the type for the
specified object, but the getClass() loses the generic type
information because of the Type Erasure feature of Java.

how to add json object to a json element in spring

i want to make a json object where it looks like
{
"version": "1.0",
"message": {
"ID": "test",
"Text": "Acd"
}
}
i need to post this data to server i am trying to add a json object to a json object how to do it
org.json.JSONObject json = new org.json.JSONObject();
org.json.JSONObject root = new org.json.JSONObject();
root.put("version", "1.0");
json.put("ID", "test");
json.put("Text", "acd");
root.put("message", json);
i am getting root.put is not a method for(string,jsonobject)
Create a Map for nested json object, like this:
Map json = new HashMap();
org.json.JSONObject root = new org.json.JSONObject();
root.put("version", "1.0");
json.put("ID", "test");
json.put("Text", "acd");
root.put("message", json);
According to doc:
Put a key/value pair in the JSONObject, where the value will be a
JSONObject which is produced from a Map.

Parsing nested JSON array in android

I am trying to parse this json in android and displaying the contents in list.
I am able to retrieve title,location and creator but dont know how to get inside des_update and retrieve text on '0'
[
{
"title": "my event ",
"location": "Chennai, Tamil Nadu, India",
"creator": "abc",
"des_update": {
"0": "this is my event with moderator"
}
},
{
"title": "my event 17",
"location": "pune",
"creator": "abc",
"des_update": {}
}
]
this is my parsing code I want to display data in alist
// convert json string to json array
JSONArray aJson = new JSONArray(sJson);
// create apps list
List<events> apps = new ArrayList<events>();
for(int i=0; i<aJson.length(); i++) {
JSONObject json = aJson.getJSONObject(i);
events app = new events();
app.setTitle(json.getString("title"));
app.setDate(json.getString("date"));
app.setLocation(json.getString("location"));
// add the app to apps list
apps.add(app);
...
}
you can use the following code:
JSONArray jsonArray = new JSONArray(json);
JSONObject object = jsonArray.getJSONObject(0);
JSONObject desObject = object.getJSONObject("des_update");
String data = desObject.getString("0");
System.out.println(data);
Here first you are loading your json string into JSONArray, and then you are taking one object from JSONArray instance. As des_update is an object with in the object you need to get that object calling getJSONObject() by passing your key and from there you can load the data that you want to use.
JSONArray jsonArray = new JSONArray(jsonString);
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject object = jsonArray.getJSONObject(i);
String title = object.getString("title");
String location = object.getString("location");
String creator = object.getString("creator");
JSONObject des_update = object.getJSONObject("des_update");
String str = des_update.getString("0");
System.out.println("des_update-------" + str);
}