How to dynamically create a JSON object in c# (from an ASP.NET resource file)? How to dynamically create a JSON object in c# (from an ASP.NET resource file)? asp.net asp.net

How to dynamically create a JSON object in c# (from an ASP.NET resource file)?


If you're using C# 4.0, you should look at the magical System.Dynamic.ExpandoObject. It's an object that allows you to dynamically add and remove properties at runtime, using the new DLR in .NET 4.0. Here is a good example use for the ExpandoObject.

Once you have your fully populated ExpandoObject, you can probably easily serialize that with any of the JSON libraries mentioned by the other excellent answers.


This sounds like an accident waiting to happen (i.e. creating output prior to cementing the structure), but it happens.

The custom JSON serializer is a compelling option, as it allows you to easily move from your dictionary into a JSON format. I would look at open source libraries (JSON.NET, etc) to see if you can reduce the development time.

I also think setting up in a slightly more structured format, like XML, is a decent choice. It is quite easy to serialize from XML to JSON using existing libraries, so you avoid heavy customization/

The bigger question is what purposes will the data ultimately serve. If you solve this problem using either of these methods, are you creating bigger problems in the future.


Probably I would use JSON.NET and the ability to create JSON from XML.

Then, you could create an XML in-memory and let JSON.NET convert it to JSON for you. Maybe if you dig deeper into the API, there are other options, too.