Serializing an object containing a Dictionary such that the Dictionary keys/values are rendered as part of the containing object

13,010

Solution 1

If you want to use JSON.Net and you're willing to change the type of your dictionary from Dictionary<string, string> to Dictionary<string, object>, then one easy way to accomplish this is to add the [JsonExtensionData] attribute to your dictionary property like this:

public class Usage
{
    public string app { get; set; }

    [JsonExtensionData]
    public Dictionary<string, object> KVPs { get; set; }
}

Then you can serialize your object like this:

string json = JsonConvert.SerializeObject(usage);

This will give you the JSON you want:

{"app":"myapp","k1":"v1","k2":"v2"}

And the bonus is, you can deserialize the JSON back to your Usage class just as easily if needed. Any properties in the JSON that do not match to members of the class will be placed into the KVPs dictionary.

Usage usage = JsonConvert.DeserializeObject<Usage>(json);

Solution 2

not pretty but this would work...

usage.KVPs["app"] = usage.app;
json = new JavaScriptSerializer().Serialize(usage.KVPs)
Share:
13,010
toosensitive
Author by

toosensitive

wandering

Updated on June 04, 2022

Comments

  • toosensitive
    toosensitive almost 2 years

    I have a class as follows:

    public class Usage
    {
        public string app { get; set; }
    
        public Dictionary<string, string> KVPs { get; set; }
    }
    

    When I use this code:

    var json = new JavaScriptSerializer().Serialize(usage);
    

    it gives me this JSON:

    {"app":"myapp", "KVPs":{"k1":"v1", "k2":"v2"}}
    

    I'd like it to return something like this instead:

    {"app":"myapp", "k1":"v1", "k2":"v2"}
    

    Is there a way to do this? I am currently using the JavaScriptSerializer. If there is a way to do this using JSON.Net, I would be willing to switch to that.

  • toosensitive
    toosensitive about 10 years
    thanks. That will work
  • Robert Levy
    Robert Levy about 10 years
    please click the little checkmark icon if this is the answer you want to accept