序列化Dictionary< string,string>到“名称"数组:"value" [英] Serializing Dictionary<string,string> to array of "name": "value"

查看:213
本文介绍了序列化Dictionary< string,string>到“名称"数组:"value"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have this simple model in an ASP.NET WebAPI 2 application:

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

序列化后,输出为:

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

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

I searched the problem, but it seems most people need this serialization:

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

所有解决方案都可以解决这种序列化问题.但是我要寻找的是将字典序列化为以下格式:

And all solutions out there are resolving to that kind of serialization. But what I'm looking for is to serialize the dictionary into this format:

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

换句话说,我想将其序列化为一个对象数组,每个对象包含一对"name1": "value1"对.有什么办法吗?还是我应该寻找其他类型?

In other words, I want to serialize it into an array of objects containing one "name1": "value1" pair each. Is there any way to do that? Or I should be looking for another type?

推荐答案

您可以使用自定义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

这篇关于序列化Dictionary&lt; string,string&gt;到“名称"数组:"value"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆