我在Web API项目中使用了Dictionary,该项目的序列化方式类似于JSON:
{"keyname":{objectvalue},"keyname2:"....
因为我有重复的键,所以我不能再使用Dictionary类型,而现在我正在使用 List<KeyValuePair<string,object>>.
List<KeyValuePair<string,object>>.
但这是以这种方式序列化的:
[{"Key":"keyname","Value":"objectvalue"}...
有没有List<KeyValuePair>办法像字典一样进行序列化?
List<KeyValuePair>
谢谢。
如果您使用Newtonsoft Json.NET库,则可以执行以下操作。
定义一个转换器,以所需的方式写入键/值对的列表:
class MyConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { List<KeyValuePair<string, object>> list = value as List<KeyValuePair<string, object>>; writer.WriteStartArray(); foreach (var item in list) { writer.WriteStartObject(); writer.WritePropertyName(item.Key); writer.WriteValue(item.Value); writer.WriteEndObject(); } writer.WriteEndArray(); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { // TODO... } public override bool CanConvert(Type objectType) { return objectType == typeof(List<KeyValuePair<string, object>>); } }
然后使用转换器:
var keyValuePairs = new List<KeyValuePair<string, object>> { new KeyValuePair<string, object>("one", 1), new KeyValuePair<string, object>("two", 2), new KeyValuePair<string, object>("three", 3) }; JsonSerializerSettings settings = new JsonSerializerSettings { Converters = new [] {new MyConverter()} }; string json = JsonConvert.SerializeObject(keyValuePairs, settings);
这产生 [{"one":1},{"two":2},{"three":3}]
[{"one":1},{"two":2},{"three":3}]