Example model:
public class Thing
{
[JsonProperty("foo")]
public string Foo {get;set;}
[JsonProperty("bars")]
public Dictionary<string,string> Bars {get;set;}
}
i want the output to look like this:
{"foo":"Foo Value", "bars":{"key1":key1Value,"key2":key2Value}}
The reason I want the values of the Dictionary to be without quotes is so I can pull the value from the client via jquery:
{"foo":"Foo Value", "bars":{"key1":$('#key1').val(),"key2":$('#key2').val()}}
Is this possible using Json.Net?
DDiVita
This is my implementation I came up with:
public class DictionaryConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Dictionary<string, string>);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var items = (Dictionary<string, string>)value;
writer.WriteStartObject();
foreach (var item in items)
{
writer.WritePropertyName(item.Key);
writer.WriteRawValue(item.Value);
}
writer.WriteEndObject();
writer.Flush();
}
}
This post helped too.
来源:https://stackoverflow.com/questions/9254820/how-to-serialize-a-dictionarystring-string-and-not-surround-the-value-with-quo