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.
There might be a specific situation, where this extension might come in handy.
Hope you find it useful.
Happy Coding !!
Top comments (0)