![](/img/trans.png)
[英]Cannot deserialize the current JSON object (e.g. {“name”:“value”}) into type requires a JSON array (e.g. [1,2,3]) to deserialize correctly
[英]Cannot deserialize the current JSON object because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly
我剛開始使用 Newtonsoft JSON.Net 在 C# 中使用 JSON,並且在反序列化以下響應時遇到問題。 這是它的第一部分。
"response":{
"sxt_func_ack":
{"sxt_func_ack":
[
{"coNo":1,"correlation_data":"","data1":"11036990-00","errorNo":0 ...}
]
},
這是 class 的開頭
public class response_cls : Response
{
public response_cls()
{
sxapi_oehdr = new Generic.List<sxapi_oehdr_cls>();
sxapi_oeitm = new Generic.List<sxapi_oeitm_cls>();
sxt_func_ack = new Generic.List<sxt_func_ack_cls>();
}
public Generic.List<sxt_func_ack_cls> sxt_func_ack { get; set; }
public Generic.List<sxapi_oehdr_cls> sxapi_oehdr { get; set; }
public Generic.List<sxapi_oeitm_cls> sxapi_oeitm { get; set; }
}
我需要對 class 做什么才能反序列化此數據?
謝謝。
你的 json 中的方括號表示該屬性是一個集合。 從您的摘錄中有點不清楚,但我可以想到兩個適合您提供的示例的模式。 兩者都使用以下代碼成功反序列化:
class Program
{
static async Task Main(string[] args)
{
var json = await File.ReadAllTextAsync("json1.json");
Body body = JsonConvert.DeserializeObject<Body>(json);
}
}
首先,兩個sxt_func_ack
屬性是不同類型的:
public class Body
{
public Response Response { get; set; }
}
public class Response
{
public Class1 Sxt_func_ack { get; set; }
}
public class Class1
{
public IEnumerable<Class2> Sxt_func_ack { get; set; }
}
public class Class2
{
public int CoNo { get; set; }
public string Correlation_data { get; set; }
public string Data1 { get; set; }
public int ErrorNo { get; set; }
}
在第二個中,兩個sxt_func_ack
屬性都是同一類型:
public class Body
{
public Response Response { get; set; }
}
public class Response
{
public Class1 Sxt_func_ack { get; set; }
}
public class Class1
{
public IEnumerable<Class1> Sxt_func_ack { get; set; }
public int CoNo { get; set; }
public string Correlation_data { get; set; }
public string Data1 { get; set; }
public int ErrorNo { get; set; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.