簡體   English   中英

序列化 KeyValuePair<TKey, TValue> 在 C# 中將屬性類型轉換為 JSON

[英]Serializing KeyValuePair<TKey, TValue> type property to JSON in C#

我正在嘗試在 C# 中序列化一個 KeyValuePair 屬性,如下所示:

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

通過將屬性設置為 JSON:

MyClass.Custom = new KeyValuePair<string, string>("destination", destination);

但我得到的輸出看起來像這樣:

"custom":{"Key":"destination","Value":"Paris"}

相反,我想要:

"custom":{"destination":"Paris"}

有什么想法嗎? 我正在使用 Compact Framework 和 Visual Studio 2008,所以我不想使用任何外部庫。 非常感謝您的幫助。

更新:我必須使用我公司的 Model 類,它有一個 SetCustom 方法,如果我使用字典,則會引發異常。

您可以使用字典而不是鍵值對

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));
    }
}

這將產生

{"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));
    }
}

不要忘記從 NuGet Newtonsoft.Json 下載

class Program
{
    static void Main(string[] args)
    {
        String [,] arr = new String[1,2];
        arr[0,0] = "Hello";
        arr[0,1] = "World";

        Console.WriteLine(JsonConvert.SerializeObject(arr));
        Console.ReadKey(true);
        //[["Hello","World"]]
    }
}

我和OP有同樣的問題,鮑勃的回答對我有用。 只是想分享一下,如果您在 .NET Core / .NET 5+ 中使用 System.Text.Json.Serialization 而不是 Newtonsoft.Json,則最終代碼會有所不同。

public class StringKeyValuePairConverter : JsonConverter<KeyValuePair<string, string>>
{
    public override KeyValuePair<string, string> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        throw new NotImplementedException();
    }

    public override void Write(Utf8JsonWriter writer, KeyValuePair<string, string> value, JsonSerializerOptions options)
    {
        writer.WriteStartObject();
        writer.WritePropertyName(value.Key);
        writer.WriteStringValue(value.Value);
        writer.WriteEndObject();
    }
}

它幾乎是相同的,除了value是強類型的,消除了強制轉換的需要,並且使用WriteStringValue (或適當的特定於類型的變體)代替WriteValue

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM