How do I create a Json Object dynamically? - json

I want to create a Json object from the below string using Java
{"attributes":{"numvcpus":1,"memsize":3072},"id":"OS Node","type":"image"}
If I know that the string will be what it is , I can create a Json object like this
JsonObject jObj = Json.createObjectBuilder()
.add("attributes",Json.createObjectBuilder()
.add("numvcpus",1)
.add("memsize",3072))
.add("id", "OS node")
.add("type": "image").build();
But the problem here is I don't know how many values will come in the nested json object i.e, the json object which is the value for "attributes" field. There may be additional fields like "disksize": 30, "lcpu": 4 etc . Is there any way to dynamically create Json objects, using for loop, while loop ?

Related

How to replace a JSON value stored in a JSON file and use that in a Rest Assured test

I have a set of input data files in JSON and I am trying to replace a value present in a JSON file and use that value to do a post request in restAssured
The JSON file has
{
"items": [
{
"item_ref": 241,
"price": 100
}
]
}
jsonbody below is a String of the above JSON file
This is the code that fails:
JSONObject jObject = new JSONObject(jsonbody);
jObject.remove("item_ref");
jObject.put("item_ref","251");
System.out.println(jObject);
This is what I am getting:
{"item_ref":"251","items":[{"item_ref":241,"price":100}]}
What I want is {"items":[{"item_ref":251,"price":100}]}
I also tried
JSONObject jObject = new JSONObject(jsonbody);
jObject.getJSONObject("items").remove("item_ref");
jObject.getJSONObject("items").put("item_ref","251");
System
But it says JSONObject["items"] is not a JSONObject.
All I need is to replace the 241 with 251. Is there an easier way to do this?
In general if we have a predefined JSON body file and if we want to replace some of the values in the body and use that in our POST calls within RestAssured, is there any easier way to do it?
The problem is - field item_ref and price are not in JSON Object as you think they are.
They are in JSON Array which contains JSON Objects. In order to modify that value, you have to get elements of the array and THEN execute very similar code you wrote.
Check this out:
JSONObject jObject = new JSONObject(jsonbody);
JSONArray array = jObject.getJSONArray("items");
JSONObject itemObject = (JSONObject) array.get(0); //here we get first JSON Object in the JSON Array
itemObject.remove("item_ref");
itemObject.put("item_ref", 251);
The output is:
{"items":[{"item_ref":251,"price":100}]}
Also, you can create a Hashmap:
HashMap<String,String> map = new HashMap<>();
map.put("key", "value");
RestAssured.baseURI = BASE_URL;
RequestSpecification request = RestAssured.given();
request.auth().preemptive().basic("Username", "Password").body(map).put("url");
System.out.println("The value of the field after change is: " + map.get("key"));

How to extract value from a nested json array?

i have a json object which contains json data with a key. now i want to extract value from that json object like name, address etc and store them to variables.
controller
json_arr = new JSONArray(j_str);
int count = json_arr.length();
json_o.put("user", json_arr);
j_str contains following data
[{"Bollywood":[{"actor":[{"name":"AA","gender":"Male"},{"name":"BB","gender":"Male"}]}]},{"Hollywood":[{"actor":[{"name":"CC","gender":"Male"},{"name":"DD","gender":"Male"}]}]}]
now it is converted to json object -- json_o ,, putting a key --- "user". now how can get a specific data such as 2nd actor name from hollywood. (i.e value DD). after then store that to a string.
Short answer: Use Jackson to map the json string to a java object, and then extract that value as a variable.
Here is a quick guide on doing this with jackson: http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/

Remove JSON object from array

I am using this to serialize my data to object in vb.net Newtonsoft.Json But what I want to do, is to delete object from my event array. The first one (index 0).
I know that can create a class and a list, but the data I get is changing from call to call.
Dim msg As String = Encoding.UTF8.GetString(message.Body)
Dim imgageInfo As Object = JsonConvert.DeserializeObject(Of Object)(msg)
MsgBox(imgageInfo("event")(0)("settings").ToString)
You could deserialize the object into a dictionary and make adjustments to the array from there.
JsonConvert.DeserializeObject<Dictionary<string, string>>(msg);
Maybe a sample of your json would help.

JsonConvert.DeserializeObject

I am trying to DeserializeObject but have not idea how to reach the object within the brackets []
dynamic response = null;
response = JsonConvert.DeserializeObject(apiResponseContent);
apiResponseContent =
"CasinoId: " + response.Result.FirstName + "\r\n" +
"PlayerId: " + response.Result.Id
The response which I am trying to parse it:
"{\"Status\":{\"ErrorCode\":0,\"ErrorName\":\"SUCCEED\",\"ErrorMessage\":\"\",\"ReferenceNumber\":\"\"},\"Result\":[{\"FirstName\":Adam,\"Id\":6161999\"}]}"
Would appreciate as answer
I believe you can access fields in the JSON object using a key collection, so response["keynamehere"].
But the best way is to create an object that mimics the objects and fields of your JSON object, and then you can deserialize to that object and it will map the fields. (ie: JsonConvert.DeserializeObject<YOUROBJECTHERE>(apiResponseContent))
Please see some reference links on how to do that in more detail:
http://www.newtonsoft.com/json/help/html/DeserializeObject.htm
Deserializing JSON data to C# using JSON.NET
If you want to get a bit more fancy, you can create your own custom converter:
Deserialize the JSON where the values are field names with JSON.NET

random selection from JSON

I try to convert some JSON string data from JSON object into an array.
When I loop over the JSON is it assign the JSON strings into diffrent array cells, eventually I get all the strings from the JSON but in diffrent order in the array each time I run the program.
for (var i:String in data)
{
// get panel tabs and players for each tab
for (var f:String in data[i].tabs)
{
tabsNames.push(f);
}
}
sometimes tabsNames = [ 1,2,3]
sometimes tabsNames = [ 2,3,1] etc'
I cant use sort because I cant know the type of the information that I will get from the JSON.
A JSON object is an unordered set of name/value pairs:
"obj" : {"propA" : "valueA", "propB":"valueB"}
A JSON array is an ordered collection of values:
"arr" : ["propA":"valueA", "propB":"valueB"]
If your data will be stored in JSON Object as list, you always get data in same order.