Seth Johnson Seth Johnson - 6 months ago 94
JSON Question

Using C# Dictionary to serialize json query string

So I am using the Dictionary class to serialize C# into JSON.

I am trying to serialize to this string

{ "User":{ "$inQuery":{ "where":{ "firstName":"plf.UserName" } } }


I am trying to assemble it with a nested group of Dictionaries. Like so..

var dict4 = new Dictionary<string, string>() { {"firstName", plf.UserName} };
var dict3 = new Dictionary<string, Dictionary<string, string>>() { { "where", dict4 } };
var dict2 = new Dictionary<string, Dictionary<string, Dictionary<string, string>>>() { { "$inQuery", dict3 } };
var dict1 = new Dictionary<string, Dictionary<string, Dictionary<string, Dictionary<string, string>>>>() {{ "User", dict2 } };


Surely this cannot be the best way to go about this.

How can I do this cleaner?

Answer

You can use anonymous classes to define your JSON structure, like this:

var json = JsonConvert.SerializeObject(
    new
    {
        User = new
        {
            inQuery = new
            {
                where = new {firstName = plf.UserName}
            }
        }
    });

However, note that I had to remove the $ from $inQuery for that to work, because C# identifiers cannot contain a dollar-sign.

You can override the names that JSON.Net will use for a property, but you can't do it with anonymous classes - you have to define a named class:

class JsonUser
{
    [JsonProperty("$inQuery")]
    public object inQuery { get; set; }
}

And then you use it like this:

var json = JsonConvert.SerializeObject(
    new
    {
        User = new JsonUser
        {
            inQuery = new
            {                            
                where = new { firstName = plf.UserName}
            }
        }
    });