DEV Community

Debashish Pal
Debashish Pal

Posted on

3 1

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

...

...

...

...

...

...

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

void Main()
{
Employee employee = new Employee() { FirstName = "Debashish", LastName = "Pal", Salary = 50000 };
Console.WriteLine(employee);
var dynamicFields = new Tuple<string, object>[3];
dynamicFields[0] = Tuple.Create("Phone No", (object) 332847398);
dynamicFields[1] = Tuple.Create("Address", (object) "some dummy address");
dynamicFields[2] = Tuple.Create("Gender", (object) "Male");
string json = employee.AddFieldsAndConvertToJson(dynamicFields);
Console.WriteLine(json);
}
class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Salary { get; set; }
}
public static class JsonExtensions
{
public static string AddFieldsAndConvertToJson(this object source, params Tuple<string, object>[] fields)
{
var jObject = JObject.FromObject(source);
var enumerator = fields.GetEnumerator();
while (enumerator.MoveNext())
{
var field = enumerator.Current as Tuple<string, object>;
jObject.AddFirst(new JProperty(field.Item1, field.Item2));
}
var json = jObject.ToString();
return 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 !!

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay