DEV Community 👩‍💻👨‍💻

Debashish Pal
Debashish Pal

Posted on

Solve the scenario - using JObject in Dotnet

Use Case:

We have this Object and you want to convert it into JSON.
Sounds simple. Right !!

However, the trick here is that you need to add couple of fields dynamically to the object, before converting.

Take a pause

Think about the solution


Think again

Scroll down for the solution








Run the below code in Linqpad (, to see it working.

Make sure you press F4, and add the Nuget package i.e. Newtonsoft.Json

I have created this extension method AddFieldsAndConvertToJson. We are simply passing array of tuple's with the required field name & data to the extension.

Check the output below. The fields are getting added to the employee object dynamically, and the JSON is being outputted.

Alt Text

There might be a specific situation, where this extension might come in handy.

Hope you find it useful.

Happy Coding !!

Top comments (0)

👋 Every week new members join DEV and share a bit about them in our Welcome Thread

Welcome them to DEV and share a bit about yourself