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 soluti…


This content originally appeared on DEV Community and was authored by Debashish Pal

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 are pressing F4, and adding 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 !!


This content originally appeared on DEV Community and was authored by Debashish Pal


Print Share Comment Cite Upload Translate Updates
APA

Debashish Pal | Sciencx (2021-04-23T16:13:18+00:00) Solve the scenario – using JObject in Dotnet. Retrieved from https://www.scien.cx/2021/04/23/solve-the-scenario-using-jobject-in-dotnet/

MLA
" » Solve the scenario – using JObject in Dotnet." Debashish Pal | Sciencx - Friday April 23, 2021, https://www.scien.cx/2021/04/23/solve-the-scenario-using-jobject-in-dotnet/
HARVARD
Debashish Pal | Sciencx Friday April 23, 2021 » Solve the scenario – using JObject in Dotnet., viewed ,<https://www.scien.cx/2021/04/23/solve-the-scenario-using-jobject-in-dotnet/>
VANCOUVER
Debashish Pal | Sciencx - » Solve the scenario – using JObject in Dotnet. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/04/23/solve-the-scenario-using-jobject-in-dotnet/
CHICAGO
" » Solve the scenario – using JObject in Dotnet." Debashish Pal | Sciencx - Accessed . https://www.scien.cx/2021/04/23/solve-the-scenario-using-jobject-in-dotnet/
IEEE
" » Solve the scenario – using JObject in Dotnet." Debashish Pal | Sciencx [Online]. Available: https://www.scien.cx/2021/04/23/solve-the-scenario-using-jobject-in-dotnet/. [Accessed: ]
rf:citation
» Solve the scenario – using JObject in Dotnet | Debashish Pal | Sciencx | https://www.scien.cx/2021/04/23/solve-the-scenario-using-jobject-in-dotnet/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.