how to convert nested json payload into for Restassured POST call using Map? - rest-assured

{
"#serviceName": "75MultipleService",
"inputs": [
{
"#name": "inp1",
"value": "8",
"#type": "number"
},
{
"#name": "inp2",
"value": "8",
"#type": "number"
}
]
}
I am trying this but not understating how to pass input2
Map <String, Object> map = new HashMap<> ();
map.put("#serviceName", "75MultipleService");
map.put("inputs", Arrays.asList(new HashMap<String, Object>() {{
put("#name", "inp1");
put("value", "8");
put("#type", "number");
}}));
How to pass nested json to post request?

how to pass input2
It's just another Map, you can do like this.
Map<String, Object> input1 = Map.of("#name", "inp1", "value", "8", "#type", "number");
Map<String, Object> input2 = Map.of("#name", "inp2", "value", "8", "#type", "number");
Map<String, Object> payload = Map.of("#serviceName", "75MultipleService", "inputs", List.of(input1, input2));

Related

How to convert List<List<Map<String, String>>> into List<List<CustomObject>> in dart

I want to convert a List<List<Map<String, String>>> into List<List> a custom class, how to achieve this in dart.
How to convert this
List<List<Map<String, String>>> = [
{
"course_name": "Estimation & Quantity Surveying",
"credit": "4",
"hours": "40",
},
{
"course_name": "IDP - Industrial Design Project phase II",
"credit": "4",
"hours": "40",
}
],
[
{
"course_name": "Data Base Management System",
"credit": "4",
"hours": "40",
},
{
"course_name": "Estimation & Quantity Surveying",
"credit": "4",
"hours": "40",
},
],
];
into
List<List<StudentTimeTable>>
This is my custom class
class StudentTimeTable{
final String courseName;
final String credit;
final String hours;
}
Something like this would do the trick:
class StudentTimeTable {
final String courseName;
final String credit;
final String hours;
StudentTimeTable.fromMap(Map<String, String> map)
: courseName = map['course_name'],
credit = map['credit'],
hours = map['hours'];
#override
String toString() =>
'StudentTimeTable(courseName = $courseName, credit = $credit, hours = $hours)';
}
void main() {
List<List<Map<String, String>>> input = [
[
{
"course_name": "Estimation & Quantity Surveying",
"credit": "4",
"hours": "40",
},
{
"course_name": "IDP - Industrial Design Project phase II",
"credit": "4",
"hours": "40",
}
],
[
{
"course_name": "Data Base Management System",
"credit": "4",
"hours": "40",
},
{
"course_name": "Estimation & Quantity Surveying",
"credit": "4",
"hours": "40",
},
],
];
List<List<StudentTimeTable>> output = [
...input.map(
(subList) => [...subList.map((map) => StudentTimeTable.fromMap(map))])
];
output.forEach(print);
// [StudentTimeTable(courseName = Estimation & Quantity Surveying, credit = 4, hours = 40), StudentTimeTable(courseName = IDP - Industrial Design Project phase II, credit = 4, hours = 40)]
// [StudentTimeTable(courseName = Data Base Management System, credit = 4, hours = 40), StudentTimeTable(courseName = Estimation & Quantity Surveying, credit = 4, hours = 40)]
}
Explanation of what going on!
The solution makes use of "spread operator" which you can read more about here:
https://dart.dev/guides/language/language-tour#spread-operator
In shot, it is a easy way to create a new list and take all elements in an iterable and put into the list.
So lets see what I do:
List<List<StudentTimeTable>> output = [...input.map((subList) => ...)]
Here we define a new list which are filled with the elements from input.map. The map method are used to take each element in the input and convert it to something else. In our case we want to convert each element in our input (which are also a List) from List<Map<String, String>> to List<StudentTimeTable>
We are then mapping each List<Map<String, String>> to the value from this:
[...subList.map((map) => StudentTimeTable.fromMap(map))]
Which returns a list filled with the elements from the iterator returned from subList.map. The purpose of this map is to convert Map<String, String> into StudentTimeTable.
This is done by calling our new constructor which takes a Map<String, String>:
StudentTimeTable.fromMap(Map<String, String> map)
: courseName = map['course_name'],
credit = map['credit'],
hours = map['hours'];
The same code could have been written something like this which is properly easier to read:
final output = <List<StudentTimeTable>>[];
for (final sublist in input) {
final studentTimeTableSubList = <StudentTimeTable>[];
for (final map in sublist) {
studentTimeTableSubList.add(StudentTimeTable.fromMap(map));
}
output.add(studentTimeTableSubList);
}
And a third way would be something like this which uses "collection for" from the same link about "spread operator":
final output = [
for (final sublist in input)
[for (final map in sublist) StudentTimeTable.fromMap(map)]
];

toJson() invalid when recursively encode tree data structure

I have a Dart class that I am using as a node class for a tree data structure.
My goal here is to encode objects of this class and its child nodes recursively.
I have a toJson() method that takes the child Nodes List and calls jsonencode on them.
class Node{
String name;
Map<String, String> attributes;
List<Node> children = List<Node>();
Node(this.name, attributes) {
this.attributes = attributes;
this.children = List<Node>();
}
Node.fromJson(Map<dynamic,dynamic> _map) {
this.name = _map['name'];
this.children = new List<Node>();
this.attributes = _map['attributes'][0];
for(var i = 0; i < _map['children'].length;i++){
Node temp = new Node.fromJson(_map['children'][i]);
this.addChild(temp);
}
}
Map<String, dynamic> toJson() => {
'name': name,
'attributes': [attributes],
'children': [
...this.children.map(jsonEncode)
]
};
}
I have a unit test i created to test this functionality:
Node nodeMap = {
"name": "Name",
"attributes": [
{"#htag1": "tagval1"}
],
"children": [
{
"name": "NameChild1",
"attributes": [
{"#htag2": "tagval2"}
],
"children": []
},
{
"name": "NameChild2",
"attributes": [
{"#htag3": "tagval3"}
],
"children": []
}
]
};
UNode unodeInst = new UNode.fromJson(nodeMap);
// Act
var nodeCreate = nodeInst.toJson();
// Assert
expect(nodeCreate, equals(nodeMap));
Here is the output of my unit test
Expected: {
'name': 'Name',
'attributes': [{'#htag1': 'tagval1'}],
'children': [
{
'name': 'NameChild1',
'attributes': [{'#htag2': 'tagval2'}],
'children': []
},
{
'name': 'NameChild2',
'attributes': [{'#htag3': 'tagval3'}],
'children': []
}
]
}
Actual: {
'name': 'Name',
'attributes': [{'#htag1': 'tagval1'}],
'children': [
'{"name":"NameChild1","attributes":[{"#htag2":"tagval2"}],"children":[]}',
'{"name":"NameChild2","attributes":[{"#htag3":"tagval3"}],"children":[]}'
]
}
Which: at location ['children'][0] is '{"name":"NameChild1","attributes":[{"#htag2":"tagval2"}],"children":[]}' which expected a map
As you see its not encoding my object correctly.
I believe this is happening because when i reclusively call jsonencode this method returns a string that is placed into the children array.
I believe part of my problem is that i dont fully understand the d diffrence between jsonencode() and toJson().
It is my understanding that jsonencode() calls toJson().. but jsonencode() returns a string and toJson() returns a Map<String, dynamic>.. so i think what i want here is to call toJson() recursively and not jsonencode.
Does this sound correct?
But i cannot figure out how to do this on a list in this situation.
I have tried the following
...this.children.map(this.toJson())
but i get "The argument type 'Map<String, dynamic>' can't be assigned to the parameter type 'dynamic Function(Node)'"
...this.children.forEach((element) {element.toJson()})
but i get "Spread elements in list or set literals must implement 'Iterable'"
Does this mean i have to implement the Iterable interface in my class?
You're just using the map method incorrectly. Use the following instead.
[
...this.children.map((e) => e.toJson())
]
It's also unnecessary to use spread with a literal list or use this. You can simplify the code to just
children.map((e) => e.toJson()).toList()

Adding values to map from other map in DART

I have a map like this
Map<String, bool> siSelectedDef = {"1": true, "2": true, "3": false};
I want to loop through the map and check for the key which has a value true, and I want to add those keys inside a List<Map<String, Object>> must
i.e
must contains
[
{
"si" : "1"
},
{
"si" : "2"
}
]
can anyone help me in this, Thanks!
Map<String, dynamic> data = {'a': true, 'b': false, 'c': true};
List<Map<String, dynamic>> _list = [];
data.forEach((key, value) {
if (value) {
_list.add({'si': key});
}
});
print(_list);
please check official doc for more detailed info and other stuffs you can do with Map

Performing a post request using Rest Assured DSL

this is the body of my post request
{
"Type": "Something",
"Authentication": [
{
"Key": "key1",
"Value": "value1"
},
{
"Key": "key2",
"Value": "value2"
},
{
"Key": "key3",
"Value": "value3"
}
]
}
I am not quite sure how to simulate sending the parameters for my post request for the post payload above.
I assumed sending everything as a key value pair but have not accounted for the nesting in the Authentication which is an array. As excepted I get a 400 Bad Request.
I would appreciate understanding how to actually send the post parameters properly for this request. Does sending it in a Map make any difference apart from readability
This is my RestAssured DSL
given().
param("type", "Something").
param("key1", "value1").
param("key2", "value2").
param("key3", "value3").
header("content-type", "application/json").
when().
post("http://someURL/something").
then().
statusCode(200).
log().everything();
Just create a hash map like this:
Map<String, Object> map = new HashMap<>();
map.put("Type", "Something");
map.put("Authentication", asList(new HashMap<String, Object>() {{
put("Key", "key1");
put("Value", "value1");
}}, new HashMap<String, Object>() {{
put("Key", "key2");
put("Value", "value2");
}}, new HashMap<String, Object>() {{
put("Key", "key3");
put("Value", "value3");
}}));
And pass it to the body of REST Assured:
given().
contentType(ContentType.JSON).
body(map).
when().
post("http://someURL/something").
then().
statusCode(200).
log().everything();
You could also create a POJO instead of a map and pass it to the body if you prefer. For this to work you need to have a supported JSON serializer framework in the classpath. For example jackson-databind. See documentation for more info.
String inputPayLaod = "{
"Type": "Something",
"Authentication": [
{
"Key": "key1",
"Value": "value1"
},
{
"Key": "key2",
"Value": "value2"
},
{
"Key": "key3",
"Value": "value3"
}
]
}";
given().contentType(ContentType.JSON)
.body(inputPayLoad)
.when()
.post(url)
.then().statusCode(200);

Using a list from JSON in MVC

I am using a Utilities.Cache.Insert to insert the JSON output from a URI.
[
{
Id": 44,
"Address": "nho:87, Huston",
"Name": "Ann"
},
{
"Id": 87,
"Address": "nho:17, Texas",
"Name": "Robert"
}
...
...
]
Utilities.Cache.Insert("my_list", AddList);
Then using a "SelectListItem" List to store the "Name" and "Address"
List<SelectListItem> d = new List<SelectListItem>();
foreach (Dictionary<string, string> item in AddList)
{
d.Add(new SelectListItem() { Text = item["Name"], Value = item["Address"] });
}
However, I need a way to store all three values, "Name","Address" and "Id" so "selectListItem" cannot be used. What are the other alternatives?

Resources