gpt4 book ai didi

c# - C#定制Dictionary 接受重复的键进行序列化

转载 作者:太空宇宙 更新时间:2023-11-03 17:40:04 24 4
gpt4 key购买 nike

我需要实现一个与Dictionary类似的自定义功能,但可以插入重复的键。因此,基本上,我需要从Dictionary中获得的是将对象序列化为以下JSON的可能性:

{
"One":"Value 1",
"Two":"Value x",
"One":"Value 10",
"Two":"Value 100"
}


如您在上面看到的,我有重复的键...

有什么建议吗?重点是上面格式的JSON输出

编辑:

KeyValuePair<string,string>不起作用!

结果如下:

[{"Key":"One","Value":"Two"},{"Key":"One","Value":"Two"}]


如您所见,序列化为JSON将使Key和Value关键字排在适当的位置,在Dictionary中,Dictionary将用实际的键值替换Key,并用提供的值替换该值。

最佳答案

您可以使用List<KeyValuePair<TKey, TValue>>代替Dictionary<TKey, TValue>。在您的情况下,它将是List<KeyValuePair<string, string>>

编辑:

如果您使用Json.NET进行JSON序列化,则可以使用自定义转换器实现所需的输出。答案here提供了它(我做了些微修改):

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# - C#定制Dictionary <string,string>接受重复的键进行序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30353840/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com