如何将字符串和值分别与字典对象分开

时间:2018-05-21 10:40:12

标签: c# dictionary

我有一个类,它是我的Web API的返回类型。

班级:

public class abc
{
   public string field1{ get; set; }

   public Dictionary<string, char> field2{ get; set; }      
}

我的查询是从API返回类对象的时候。对于字典对象,结构应采用以下格式:

[{
  “field1” : “D123456XYZ”,
// for field2 in the below format
  [{ “key”: “123”
      “value”: “y”
    },
    { “key”: "456"
      “value”: “n”
    },
    { “key”: “789”
      “value”: “y”
    }

}]

怎么做?

1 个答案:

答案 0 :(得分:0)

您可以使用Json.Net库来执行此操作。您可以构造一个新的JObject并根据字典中的项目手动设置其属性。

foreach ( var pair in field2 )
{
     var item = new JObject();
     item[ pair.Key ] = pair.Value;
}

或者,您可以创建自定义转换器,只需向属性添加属性,以便自动执行此操作。

public class ObjectDictionaryConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (typeof(IDictionary).IsAssignableFrom(objectType) ||
                TypeImplementsGenericInterface(objectType, typeof(IDictionary<,>)));
    }

    private static bool TypeImplementsGenericInterface(Type concreteType, Type interfaceType)
    {
        return concreteType.GetInterfaces()
                .Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == interfaceType);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var dictionary = (IDictionary)value;
        writer.WriteStartArray();
        foreach ( var key in dictionary.Keys)
        {
            var keysValue = dictionary[key];
            writer.WriteStartObject();
            writer.WritePropertyName(key.ToString());
            writer.WriteValue(keysValue);
            writer.WriteEndObject();
        }
        writer.WriteEndArray();
    }

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

然后您可以像这样应用此自定义转换器:

public class abc
{
    public string field1 { get; set; }

    [JsonConverter(typeof(ObjectDictionaryConverter))]
    public Dictionary<string, char> field2 { get; set; }
}