将Dictionary <string,string>序列化为&#34; name&#34;:&#34; value&#34;

时间:2016-10-26 08:27:25

标签: c# serialization json.net asp.net-web-api2

我在 ASP.NET WebAPI 2 应用程序中有这个简单的模型:

public class Model {
    public int ID { get; set; }
    public Dictionary<string, string> Dic { get; set; }
}

当序列化时,输出为:

{
    "ID": 0,
    "Dic": {
        "name1": "value1",
        "name2": "value2"
    }
}

我搜索了这个问题,但似乎大多数人都需要这个序列化:

{
    "ID": 0,
    "Dic": [{
        "Key": "name1",
        "Value": "value1"
    }]
}

所有解决方案都解决了这种序列化问题。但我正在寻找的是将字典序列化为这种格式:

{
    "ID": 0,
    "Dic": [{
        "name1": "value1"
    }, {
        "name2": "value2"
    }]
}

换句话说,我想将它序列化为一个对象数组,每个对象包含一个"name1": "value1"对。有没有办法做到这一点?或者我应该寻找另一种类型?

1 个答案:

答案 0 :(得分:1)

您可以使用自定义JsonConverter来获取您正在寻找的JSON。以下是转换器所需的代码:

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]属性标记字典,如下所示:

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

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