c#自定义词典< string,string>接受重复的密钥进行序列化 [英] c# custom Dictionary<string,string> that accepts duplicate keys for serialization
问题描述
我需要实现一个与Dictionary类似的自定义功能,但可以插入重复的键.因此,基本上,我需要从Dictionary中获得的是将对象序列化为以下JSON的可能性:
I need to implement a custom functionality a bit similar Dictionary but with the possibility to insert duplicate keys. So basically what I need from Dictionary is the possibility to serialize the object as the following JSON:
{
"One":"Value 1",
"Two":"Value x",
"One":"Value 10",
"Two":"Value 100"
}
正如您在上面看到的,我有重复的键...
As you can see above I have duplicate keys ...
有什么建议吗?重点是上面格式的JSON输出
KeyValuePair< string,string>
无效!
这是结果:
[{"Key":"One","Value":"Two"},{"Key":"One","Value":"Two"}]
如您所见,序列化为JSON会使Key和Value关键字变粗,而Dictionary将使用实际的键值替换Key,并使用提供的值替换键.
As you can see serialized as JSON will brink the Key and Value keywords in place where a Dictionary will replace the Key with the actual key-value and the value with the value provided.
推荐答案
您可以使用 List< KeyValuePair< TKey,TValue>>
代替 Dictionary< TKey,TValue>
.在您的情况下,它将是 List< KeyValuePair< string,string>>
.
You can use a List<KeyValuePair<TKey, TValue>>
instead of a Dictionary<TKey, TValue>
. In your case, it would be a List<KeyValuePair<string, string>>
.
如果您使用 Json.NET
进行JSON序列化,则可以使用自定义转换器实现所需的输出.答案此处提供了答案(我做了一些修改):
If you're using Json.NET
for serialization of the JSON, you can achieve your desired output using a custom converter. The answer here provides it (I made slight modifications):
class KeyValuePairConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value,
JsonSerializer serializer)
{
var list = value as List<KeyValuePair<string, string>>;
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, string>>);
}
}
这篇关于c#自定义词典< string,string>接受重复的密钥进行序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!