且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

序列化Dictionary< string,string>到“名称"数组:"value"

更新时间:2023-11-05 13:17:52

您可以使用自定义JsonConverter来获取所需的JSON.这是转换器所需的代码:

You can use a custom JsonConverter to get the JSON you're looking for. Here is the code you would need for the converter:

public class CustomDictionaryConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return typeof(IDictionary).IsAssignableFrom(objectType);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        IDictionary dict = (IDictionary)value;
        JArray array = new JArray();
        foreach (DictionaryEntry kvp in dict)
        {
            JObject obj = new JObject();
            obj.Add(kvp.Key.ToString(), kvp.Value != null ? JToken.FromObject(kvp.Value, serializer) : new JValue((string)null));
            array.Add(obj);
        }
        array.WriteTo(writer);
    }

    public override bool CanRead
    {
        get { return false; }
    }

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

要使用转换器,请在模型类中的字典中使用[JsonConverter]属性标记,如下所示:

To use the converter, mark the dictionary in your model class with a [JsonConverter] attribute like this:

public class Model 
{
    public int ID { get; set; }
    [JsonConverter(typeof(CustomDictionaryConverter))]
    public Dictionary<string, string> Dic { get; set; }
}

演示小提琴: https://dotnetfiddle.net/320LmU