[英]c# Json.net deserializing List<Dictionary<string,object>>
[英]C# Deserializing a Dictionary<(Enum,Enum),string> with JSON.NET
我一直在努力用 Json.Net 中的枚舉元組鍵反序列化字典。 主要問題是反序列化器無法將值轉換回指定的 Enum 元組,無論它是 Enum 的字符串還是 Json 中的 integer 表示。
我已經嘗試了這些解決方案,但都沒有奏效:
嘗試編寫我自己的自定義轉換器,WriteJson 部分有效,但我什至無法用斷點停止 ReadJson function 以查看內部發生的情況。
我很樂意在這個問題上得到一些幫助。 也許有人已經有了解決方案。
JSON 看起來像這樣:
{
"DictionaryProperty":{
"(EnumType1Value1, EnumType2Value1)":"New",
"(EnumType1Value1, EnumType2Value1)":"Old",
"(EnumType1Value2, EnumType2Value1)":"Newer",
"(EnumType1Value2, EnumType2Value2)":"Older"
}
這是我得到的錯誤:
“無法將字符串 '(EnumType1Value1, EnumType2Value1)' 轉換為字典鍵類型 'System.ValueTuple`2[EnumType1,EnumType2]'”
這是我寫的自定義轉換器:
public class CustomDictionaryConverter : JsonConverter<Dictionary<(EnumType1 Enum1, EnumType2 Enum2), string>>
{
public override void WriteJson(JsonWriter writer, Dictionary<(EnumType1 Enum1, EnumType2 Enum2), string> value, JsonSerializer serializer)
{
serializer.Serialize(writer, ((Dictionary<(EnumType1 Enum1, EnumType2 Enum2), string>)value).ToList());
}
public override Dictionary<(EnumType1 Enum1, EnumType2 Enum2), string> ReadJson(
JsonReader reader
, Type objectType
, Dictionary<(EnumType1 Enum1, EnumType2 Enum2), string> existingValue
, bool hasExistingValue
, JsonSerializer serializer)
{
Dictionary<(EnumType1 Enum1, EnumType2 Enum2), string> tempdict = new Dictionary<(EnumType1 Enum1, EnumType2 Enum2), string>();
var temp = serializer.Deserialize<Dictionary<(EnumType1 Enum1, EnumType2 Enum2), string>[]>(reader)[0];
tempdict = (Dictionary<(EnumType1 Enum1, EnumType2 Enum2), string>)temp;
return tempdict;
}
}
有點手動(並且缺乏體面的錯誤檢查),但適用於您指定的 json 序列化和反序列化
public class CustomDictionaryConverter : JsonConverter<Dictionary<(EnumType1 Enum1, EnumType2 Enum2), string>>
{
public override void WriteJson(JsonWriter writer, Dictionary<(EnumType1 Enum1, EnumType2 Enum2), string> value, JsonSerializer serializer)
{
writer.WriteStartObject();
foreach(var kv in value)
{
writer.WritePropertyName($"({kv.Key.Enum1.ToString()},{kv.Key.Enum2.ToString()})");
writer.WriteValue(kv.Value);
}
writer.WriteEndObject();
}
public override Dictionary<(EnumType1 Enum1, EnumType2 Enum2), string> ReadJson(
JsonReader reader
, Type objectType
, Dictionary<(EnumType1 Enum1, EnumType2 Enum2), string> existingValue
, bool hasExistingValue
, JsonSerializer serializer)
{
Dictionary<(EnumType1 Enum1, EnumType2 Enum2), string> tempdict = new Dictionary<(EnumType1 Enum1, EnumType2 Enum2), string>();
JObject jObject = JObject.Load(reader);
foreach(var kv in ((IEnumerable<KeyValuePair<string, JToken>>)jObject))
{
var keys = kv.Key.Replace("(","").Replace(")","").Split(",");
var key1 = Enum.Parse<EnumType1>(keys[0]);
var key2 = Enum.Parse<EnumType2>(keys[1]);
var value = kv.Value.ToString();
tempdict.Add((key1,key2),value);
}
return tempdict;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.