DEV Community

tswiftma
tswiftma

Posted on

6 1

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

API Trace View

How I Cut 22.3 Seconds Off an API Call with Sentry 👀

Struggling with slow API calls? Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs