DEV Community

tswiftma
tswiftma

Posted on

Generate a JSON list for a request body payload in C# using Collection Initializers

I recently had to write a test for a new JSON REST POST API. The request body of the POST contained a formatted JSON list. Typically the body of various REST calls are JSON formatted between two brackets { json }. But in this case I needed list brackets with the JSON [{ json }] for the body.

Image description

It's easy enough to create a C# class such that an object from it represents the JSON data between the brackets { }. In the below example the class is called SettingValue.

Image description

But how in C# do you create a initialized list of this JSON that can then be used in the body of the POST? You first create an object settingValue of type SettingValue. This is our { json }. Then you create a List object settingValueList of type SettingValue.

Image description

But what is the { settingsValue } at the end of the List instantiation? It is a Collection Initializer for the List with settingValue as the Element Initializer. Only objects of type SettingValue can be added to the list and the list is now created with default settingValue JSON. If you don't use an Element Initializer, the List will not have the default value we need.

Now you can update or add to the list and pass settingValueList to use as the body for your JSON POST. So your settingValueList list might end up looking something like this:
Image description

The solution seems simple to me now but for some reason in years of API automation I never have had to do it before. Previously I had only seen nested JSON Lists [ ] within JSON brackets { } and nesting lists in JSON can be done using nested C# classes, which would be the subject of another blog post :)

PS: Thanks to Dan Post and Bob Geary for a technical review of the post

Discussion (0)