DEV Community

loading...

Solve the scenario - using JObject in Dotnet

Debashish Pal
I am Debashish Pal. Technical Architect by Profession, A Passionate Coder, Tech lover, Mad for Table Tennis. Love listening to Bollywood music !!
・1 min read

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

...

...

...

...

...

...

Solution

Run the below code in Linqpad (https://www.linqpad.net/), 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 !!

Discussion (0)