在 C# 中将 KeyValuePair<TKey,?TValue> 类型属性序列化为 JSON

Ali*_*aei 3 c# serialization json

我正在尝试序列化 C# 中的 KeyValuePair 属性,如下所示:

[JsonDisplayName("custom")]
public  KeyValuePair<string,string> Custom { get; set; }
Run Code Online (Sandbox Code Playgroud)

通过设置属性来转换为 JSON:

MyClass.Custom = new KeyValuePair<string, string>("destination", destination);
Run Code Online (Sandbox Code Playgroud)

但我得到的输出看起来像这样:

"custom":{"Key":"destination","Value":"Paris"}
Run Code Online (Sandbox Code Playgroud)

相反,我想要:

"custom":{"destination":"Paris"}
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?我正在使用 Compact Framework 和 Visual Studio 2008,因此我不喜欢使用任何外部库。非常感谢您的帮助。

更新: 我必须使用我公司的 Model 类,它有一个 SetCustom 方法,如果我使用字典,该方法会引发异常。

Bob*_*Bob 5

您可以使用字典代替键值对

public class A
{
    [JsonProperty("custom")]
    public Dictionary<string, string> Custom
    {
        get;
        set;
    }
}
public class Program
{
    public static void Main()
    {
        A custom = new A();
        custom.Custom = new Dictionary<string, string>(){
            {"destination1", "foo"},
            {"destination2", "bar"},
        };
        Console.WriteLine(JsonConvert.SerializeObject(custom));
    }
}
Run Code Online (Sandbox Code Playgroud)

这将产生

{"custom":{"destination1":"foo","destination2":"bar"}}

或者,如果您想坚持使用,KeyValuePair则需要创建自己的转换器

public class A
{
    [JsonProperty("custom")]
    public KeyValuePair<string, string> Custom
    {
        get;
        set;
    }
}

class KeyValueStringPairConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        KeyValuePair<string, string> item = (KeyValuePair<string, string>)value;
        writer.WriteStartObject();
        writer.WritePropertyName(item.Key);
        writer.WriteValue(item.Value);
        writer.WriteEndObject();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof (KeyValuePair<string, string>);
    }
}

public class Program
{
    public static void Main()
    {
        A custom = new A();
        JsonSerializerSettings settings = new JsonSerializerSettings{Converters = new[]{new KeyValueStringPairConverter()}};
        custom.Custom = new KeyValuePair<string, string>("destination", "foo");
        Console.WriteLine(JsonConvert.SerializeObject(custom, settings));
    }
}
Run Code Online (Sandbox Code Playgroud)