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);