我有下面的json
"Payload": {
"AdditionalProperties": [
{
"Key": "MyKey1",
"Value": "Value"
},
{
"Key": "MyKey2",
"Value": "Value"
}
]
}
默认情况下,这可以反序列化为对象,AdditionalProperties被反序列化为列表,其中AdditionalProperty只有两个属性Key和Value,这两个属性都是字符串
如何将上面的json反序列化为Dictionary<字符串,字符串>自动地
目前,我不得不创建一个单独的房产,这不是很好的
public List<AdditionalProperty> AdditionalProperties { get; set; }
public Dictionary<string, string> AdditionalPropertiesDictionary
{
get
{
return _additionalPropertiesDictionary ??= AdditionalProperties.ToDictionary(x => x.Key, x => x.Value);
}
set => _additionalPropertiesDictionary = value;
}
Paul
在这种情况下,我通常会创建一个JsonConstructor
Data data=JsonConvert.DeserializeObject<Data>(json);
public class Data
{
public Payload Payload { get; set; }
}
public class Payload
{
public Dictionary<string,string> AdditionalProperties { get; set; }
[JsonConstructor]
public Payload(JArray AdditionalProperties)
{
this.AdditionalProperties = AdditionalProperties
.ToDictionary(ap => (string) ap["Key"],ap=>(string)ap["Value"] );
}
}
您可以编写一个自定义转换器来反序列化它们的键值对:
public class ArrayStringDictionaryConverter : JsonConverter<Dictionary<string, string>>
{
public override void WriteJson(JsonWriter writer, Dictionary<string, string> value, JsonSerializer serializer)
=> throw new NotImplementedException();
public override Dictionary<string, string> ReadJson(JsonReader reader, Type objectType, Dictionary<string, string> existingValue, bool hasExistingValue, JsonSerializer serializer)
{
var keyValuePairs = serializer.Deserialize<IEnumerable<KeyValuePair<string, string>>>(reader);
return new Dictionary<string, string>(keyValuePairs);
}
}
然后你可以使用它如下:
var json = @"{ ""Payload"": {
""AdditionalProperties"": [
{
""Key"": ""MyKey1"",
""Value"": ""Value""
},
{
""Key"": ""MyKey2"",
""Value"": ""Value""
}
]
}
}";
var root = JsonConvert.DeserializeObject<Root>(json, new ArrayStringDictionaryConverter());
foreach(var (k, v) in root.Payload.AdditionalProperties)
{
Console.WriteLine($"k: {k}, v: {v}");
}
// k: MyKey1, v: Value
// k: MyKey2, v: Value
public class Root
{
public Payload Payload {get;set;}
}
public class Payload
{
public Dictionary<string, string> AdditionalProperties {get;set;}
}