[英]Deserialize JSON to fit Model
我的 JSON 字符串如下所示:
"[{\\r\\n\\t'variable1': [{0:'somename'}],\\r\\n\\r\\n\\t'variable2': 'xxx'\\r\\n}]"
我想反序列化這個JSON
字符串,使其適合我的Model
,如下所示:
public string variable2 { get; set; }
public List<KeyValuePair<int, string>> variable1 { get; set; }
但是, JSON
字符串的array
部分( variable1
)不會反序列化。 它檢測到int
但沒有檢測到字符串“somename”。 它只是顯示為空。
我該如何解決這個問題?
注意:我使用的是 Newtonsoft.Json
解析這個 json 的簡單方法是這樣的:
[Fact]
public void ShouldParseClass()
{
var result = JsonConvert.DeserializeObject<List<SOClass>>("[{\r\n\t'variable1': [{0:'somename'}],\r\n\r\n\t'variable2': 'xxx'\r\n}]");
Assert.True(result.First().variable1[0]["0"] == "somename");
}
public class SOClass
{
public string variable2 { get; set; }
public List<dynamic> variable1 { get; set; }
}
您的 Json 中的主要問題是varible1
是一個列表。 所有值都應該在同一個對象上才能成為字典。 另一方面,如果你想要一個 KeyValuePair 列表,你應該像這樣傳遞這些項目{'key':0,'value':'somename'}
。
這可能取決於您使用哪個庫來反序列化您的 JSON。 如果您使用的是Newtonsoft.Json ,我還建議您將List<KeyValuePair<int, string>>
更改為Dictionary<int, string>
,這樣做可能會解決您的反序列化問題。
如果您無法控制 json,則應定義自定義轉換器:
public class Data
{
public string variable2 { get; set; }
// pick one: dictionart should be favored, unless you have no-unique keys
// [JsonConverter(typeof(CustomListKvpConverter<int, string>))]
// public List<KeyValuePair<int, string>> variable1 { get; set; }
//
// [JsonConverter(typeof(CustomDictionaryKvpConverter<int, string>))]
// public Dictionary<int, string> variable1 { get; set; }
}
public class CustomListKvpConverter<TKey, TValue> : JsonConverter<List<KeyValuePair<TKey, TValue>>>
{
public override List<KeyValuePair<TKey, TValue>> ReadJson(JsonReader reader, Type objectType, List<KeyValuePair<TKey, TValue>> existingValue, bool hasExistingValue, JsonSerializer serializer)
{
return JArray.Load(reader)
.ToObject<Dictionary<TKey, TValue>[]>()
.SelectMany(x => x)
.ToList();
}
public override void WriteJson(JsonWriter writer, List<KeyValuePair<TKey, TValue>> value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
public class CustomDictionaryKvpConverter<TKey, TValue> : JsonConverter<Dictionary<TKey, TValue>>
{
public override Dictionary<TKey, TValue> ReadJson(JsonReader reader, Type objectType, Dictionary<TKey, TValue> existingValue, bool hasExistingValue, JsonSerializer serializer)
{
return JArray.Load(reader)
.ToObject<Dictionary<TKey, TValue>[]>()
.SelectMany(x => x)
.ToDictionary(x => x.Key, x => x.Value);
}
public override void WriteJson(JsonWriter writer, Dictionary<TKey, TValue> value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.