how to add json object to a json element in spring - json

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.

Related

how to convert nested payload into Java-JSONObject (net.minidev.json.JSONObject) for Restassured POST call

How to convert below nested payload into Java-JSONObject (net.minidev.json.JSONObject) for Restassured POST call request body ?
{
"object": "new_subway_group",
"name": "Group 1",
"subways": [
1,
2,
3
]
}
Setup request body, use array or List for [1,2,3]
JSONObject surveyPriceObject = new JSONObject();
surveyPriceObject.put("object", "new_subway_group");
surveyPriceObject.put("name", "Group 1");
surveyPriceObject.put("subways", Arrays.asList(1,2,3));
Convert response to JSONObject
If the response has type Response then
import net.minidev.json.JSONObject;
...
JSONObject object = res.jsonPath().getObject("", JSONObject.class);
System.out.println(object);
If the response has type String then
import io.restassured.path.json.JsonPath;
import net.minidev.json.JSONObject;
...
JSONObject object = JsonPath.from(res).getObject("", JSONObject.class);
System.out.println(object);

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
}

creating json as is shown in Postman

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

GSON - json to generic object

I have a use case where an API will get a generic collection of Key|Value pairs in json. There are no defined attributes in the input json. I need to map it to a generic object and process the data..
JSON input:
"[{ "PostalCode": "345", "Region": "MA", "Enabled": "True" },
{"PostalCode": "989", "Country": "US", "Enabled": "True" }
]";
I am using GSON to deserialize this to java object. On mapping this to a generic object like:
Object obj = new GsonBuilder().create()
.fromJson(jsonInput, Object.class);
i get a an object of Array list of HashMaps (com.google.gson.internal.LinkedTreeMap).
From here how do i get individual key and values like key = PostalCode & value = 345?
Thanks in advance for your help!
As you have already got an array list of com.google.gson.internal.LinkedTreeMap, Now you need to iterate this list to get each key value pair :
Object obj = new GsonBuilder().create().fromJson(jsonInput, Object.class);
List<LinkedTreeMap<Object, Object>> jsonMapList = (List<LinkedTreeMap<Object, Object>>) obj;
for (LinkedTreeMap<Object, Object> jsonMap : jsonMapList) {
Set<Entry<Object, Object>> entrySet = jsonMap.entrySet();
for (Entry<Object, Object> entry : entrySet) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
You can do this way. I have tested it.
import this
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
Type type = new TypeToken<List<LinkedTreeMap<Object, Object>>>(){}.getType();
List<Map<Object, Object>> treeMap = newGsonBuilder().create().fromJson(jsonInput,type);