序列化KeyValuePairc#中type属性为JSON

本文关键字:type 属性 JSON KeyValuePair TKey TValue 序列化 | 更新日期: 2023-09-27 18:06:34

我试图在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方法,如果我使用字典,该方法会抛出异常。

序列化KeyValuePair<TKey, TValue>c#中type属性为JSON

可以用字典代替键值对

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一样的问题,Bob的答案帮了我的忙。只是想分享一下,如果你在。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