首先,我建议使用newton json dll。
其次,您需要为KeyValuePair
创建自定义JsonConverter,如下所示:
public class PairConverter : JsonConverter { public override bool CanConvert(Type objectType) { return objectType == typeof(KeyValuePair<string, int>); } 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 item = (KeyValuePair<string, int>)value; writer.Writevalue(item.Value); writer.Flush(); } }
然后像这样为“年龄”属性添加JsonConverter属性:
public class Persons { [JsonConverter(typeof(PairConverter))] public KeyValuePair<string, int> Age { get; set; } }
var persons = new Persons() { Age = new KeyValuePair<string, int>("Age", 10) }; var json = JsonConvert.SerializeObject(persons); // {Age:10}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)