Iterate through JSONObject - json

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
}

Related

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

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.

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

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.

Building Json Newtonsoft Jarray

I have hours stuck on this, I dont know why I lose my json, with lose I mean it has the 'structure' but not the values. I am trying to return a JArray with JObjects of the Newtonsoft .Json library. this is a simple example, I am trying to do this with Linq, but get the same results.
I am using asp mvc, I took this example
My controller:
JArray jsonTest = new JArray(
new JObject
{
{"Title", "hello"},
{
"Author", new JObject
{
{"Name", "hello"},
{"Twitter", "hello"}
}
},
{"Date", "hello"},
{"BodyHtml", "hello"},
},
new JObject
{
{"Title", "hello"},
{
"Author", new JObject
{
{"Name", "hello"},
{"Twitter", "hello"}
}
},
{"Date", "hello"},
{"BodyHtml", "hello"},
}
);
return Json(jsonTest,JsonRequestBehavior.AllowGet);
and I get:
as you can see my structure is there(2 objects, second object is an array with 2 elements), but i have no data in it.
I tried jsonTest.tostring() but I get an array of each char in my string.
What am I missing?
Add the two JObjects into an Jarray
like
JObject obj1=new JObject();
JObject obj2=new JObject();
JArray arr=new JArray();
arr.Add(obj1);
arr.Add(obj2);
return arr.ToString(Newtonsoft.Json.Formatting.Indented);