示例模型:
public class Thing
{
[JsonProperty("foo")]
public string Foo {get;set;}
[JsonProperty("bars")]
public Dictionary<string,string> Bars {get;set;}
}
我希望输出看起来像这样:
{"foo":"Foo Value", "bars":{"key1":key1Value,"key2":key2Value}}
我希望Dictionary的值没有引号的原因是我可以通过jquery从客户端获取值:
{"foo":"Foo Value", "bars":{"key1":$('#key1').val(),"key2":$('#key2').val()}}
这可以使用Json.Net吗?
答案 0 :(得分:1)
这是我提出的实施方案:
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也有帮助。