How to create JSON object in c# without class [dynamically]

/ / 0 Comments

Create a JSON object dynamically: Here in this article, we are going to see how we can create JSON objects on the fly. Yes, we can create a JSON object dynamically in C# without creating a class object.  In C# application using newtonsoft library, makes working with JSON very easy.

First, we have to add Newtonsoft from the NuGet package manager into our project. Then add namespaces Newtonsoft.Json.Linq as written below:

 using Newtonsoft.Json.Linq;


Now we have everything, from which we able to generate JSON string dynamically. We are going to use Dynamic datatype and initialize a new instance of the JObject() class. Then we can add whatever value we want to add to this obj variable.

Also Read: 3 Ways Convert Datatable to JSON in C#

C# code to generate a dynamic JSON string

We have created a method CreateJson() which returns us JSON string.

public string CreateJson() 
{
	dynamic obj = new JObject();
	obj.Name = "Satinder Singh";
	obj.Location = "Mumbai";
	obj.blog = "Codepedia.info";
	
	var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
	return jsonString;
} 

Here in the preceding code with JsonConvert.SerializeObject we serialize our object and get JSON string.

Output:


Conclusion: By using dynamic datatype and Newtonsoft library we can easily able to create dynamic JSON in C# without any class.

Other Reference:

Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.

PS: If you found this content valuable and want to do a favor, then Buy me a coffee

Subscribe to our newsletter

Get the latest and greatest from Codepedia delivered straight to your inbox.


Post Comment

Your email address will not be published. Required fields are marked *

0 Comments