4

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.

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
toosensitive
  • 2,335
  • 7
  • 46
  • 88

2 Answers2

9

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);
Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
2

not pretty but this would work...

usage.KVPs["app"] = usage.app;
json = new JavaScriptSerializer().Serialize(usage.KVPs)
Robert Levy
  • 28,747
  • 6
  • 62
  • 94