Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I need to serialize the strings from a resource file (.resx) into a JSON object. The resource file's keys are in flux and thus I cannot just create a C# object that accepts the appropriate values. It needs to be a dynamic solution. I am able to loop through the key-value pairs for the file, but I need an easy way to serialize them to JSON.

I know I could do:

Object thing = new {stringOne = StringResource.stringOne; ...}

But, I'd rather have something like:

Object generic = {}
foreach (DictionaryEntry entry in StringResource) {
    generic.(entry.Key) = entry.Value
}

Or should I just create a custom JSON serializer that constructs the object piecemeal (i.e. foreach loop that appends part of the JSON string with each cycle)?

EDIT
I ended up writing a quick JSON serializer that constructs the string one field at a time. I didn't want to include a whole JSON library as this is the only use of JSON objects (for now at least). Ultimately, what I wanted is probably impractical and doesn't exist as it's function is better served by other data structures. Thanks for all the answers though!

like image 243
Collin M Avatar asked Jul 07 '11 16:07

Collin M


2 Answers

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.

like image 130
Phil Avatar answered Sep 20 '22 23:09

Phil


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.

like image 35
Gregory A Beamer Avatar answered Sep 22 '22 23:09

Gregory A Beamer