![](/img/trans.png)
[英]json newtonsoft : Deserialize Object containing a list of string
[英]Deserialize a Json containing a list of object
我在UniversalApp上工作,該應用程序調用了許多返回JSON數據的Web服務。
所有的Web服務都向我返回了Json的第一級( WsResponse.cs ),其中包含以下結構:
public string status { get; set; }
public object data { get; set; }
public List<object> errors { get; set; }
如果狀態為“ 成功 ”,則可以通過以下方式反序列化簡單數據對象:
WsResponse wsResponse = JsonConvert.DeserializeObject<WsResponse>(response);
User user = JsonConvert.DeserializeObject<User>(wsResponse.data.ToString());
在其他情況下,必須先在結果對象中反序列化,然后再反序列化數據:
WsResponse wsResponse = JsonConvert.DeserializeObject<WsResponse>(response);
WsResponseResult wsResponseResult = JsonConvert.DeserializeObject<WsResponseResult>(
wsResponse.data.ToString());
List<Theme> themes = JsonConvert.DeserializeObject<List<Theme>>(
wsResponseResult.result.ToString());
但是,如果狀態為“ failure ”,則需要捕獲錯誤列表。 但是我無法反序列化此對象列表...這是一個當Web服務包含錯誤時從Web服務獲取的JSON數據的示例:
{
"status": "failure",
"data": {},
"errors": [
{
"200": "The parameter 'email' is not present"
},
{
"200": "The parameter 'password' is not present"
}
]
}
我嘗試通過以下方式反序列化:
List<KeyValuePair<string, string>> kvpError = new List<KeyValuePair<string,string>>();
kvpError = JsonConvert.DeserializeObject<List<KeyValuePair<<string, string>>>(
wsResponse.errors.ToString());
Dictionary<string, string> dError = new Dictionary<string, string>();
dError = JsonConvert.DeserializeObject<Dictionary<string, string>>(
wsResponse.errors.ToString());
=>但它不起作用
我還嘗試對錯誤數據進行反序列化之前將它們反序列化:
foreach(var error in wsResponse.errors)
{
KeyValuePair<string, string> kvpError = new KeyValuePair<string,string>();
kvpError = JsonConvert.DeserializeObject<KeyValuePair<string, string>>(
error.ToString());
}
=>但效果不佳...
您對如何解決我的問題有想法嗎?
JSON的結構errors
實際上是一個List<Dictionary<string, string>>
。 如果使用它代替List<object>
,它將正確反序列化錯誤:
public class Response
{
public string status { get; set; }
public object data { get; set; }
public List<Dictionary<string, string>> errors { get; set; }
}
產量:
旁注-如果您可以控制JSON結構,最好使用單個List<KeyValuePair<string, string>>
進行反序列化。 另外,實際上不傳遞object data
,而是在JSON內傳遞User
屬性,這樣您就可以避免雙重反序列化。
如果您希望將其反序列化為List<KeyValuePair<string, string>>
,則您的JSON需要如下所示:
{
"status": "failure",
"data": {},
"errors": [
{
"Key": "200", "Value": "The parameter 'email' is not present"
},
{
"Key": "200", "Value": "The parameter 'password' is not present"
}
]
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.