[英]JsonConvert.DeserializeObject is not working when deserializing to a DataSet
I was trying to convert a JSON string to a dataset but it's throwing an error:我试图将 JSON 字符串转换为数据集,但它抛出了一个错误:
Unexpected JSON token when reading DataTable.
读取 DataTable 时出现意外的 JSON 令牌。 Expected StartArray, got StartObject.
预期 StartArray,得到 StartObject。 Path 'data', line 1, position 9.
路径“数据”,第 1 行,position 9。
from the DataSet dataSet = (DataSet)JsonConvert.DeserializeObject(json, (typeof(DataSet)));
来自
DataSet dataSet = (DataSet)JsonConvert.DeserializeObject(json, (typeof(DataSet)));
line.线。
The JSON response from server looks fine;来自服务器的 JSON 响应看起来不错; here is my code:
这是我的代码:
public void GlobalApiCall(string API_Name, string postData)
{
ConnectionClass t1 = new ConnectionClass();
var link = ConfigurationManager.AppSettings["ReportUrl"];
var request1 = (HttpWebRequest)WebRequest.Create(link + API_Name);
var data1 = Encoding.ASCII.GetBytes(postData);
request1.Method = "POST";
request1.ContentType = "application/x-www-form-urlencoded";
request1.ContentLength = data1.Length;
using (var stream = request1.GetRequestStream())
{
stream.Write(data1, 0, data1.Length);
}
var response1 = (HttpWebResponse)request1.GetResponse();
var responseString1 = new StreamReader(response1.GetResponseStream()).ReadToEnd();
String json = responseString1.Replace("\"", "'");
DataSet dataSet = (DataSet)JsonConvert.DeserializeObject(json, (typeof(DataSet)));
}
and my JSON response:和我的 JSON 响应:
{
"data": {
"Table": [
{
"FirmId": 67,
"FirmName": "FURNITURE ELECTRONICS & HOME APPLIANCES ",
"BranchId": 44317,
"BranchName": " PERINTHALMANNA",
"Address": "PERINTHALMANNA",
"Contact": "123456",
"HelpLine": "454656",
"MailId": "qwerty@GMAIL.COM",
"GSTINNo": "wewrerw",
"BranchRegNo": "08/2019",
"PAN": "rwerewr",
"OtherNotes": "",
"State": "KERALA",
"StateCode": "32",
"Delivery": "Y"
}
]
}
}
I am unable to find the issue.我无法找到问题。 Where should I start looking?
我应该从哪里开始寻找?
You are getting this error because the JSON is not in the format that the deserializer is expecting in order to be converted to a DataSet
.您收到此错误是因为 JSON 不是反序列化器期望转换为
DataSet
的格式。 In particular, the DataSet data appears to be wrapped in an outer object.特别是,DataSet 数据似乎包装在外部 object 中。 Try deserializing the JSON like this instead:
尝试像这样反序列化 JSON :
DataSet dataSet = JObject.Parse(json)["data"].ToObject<DataSet>();
Fiddle: https://dotnetfiddle.net/aOiaeH小提琴: https://dotnetfiddle.net/aOiaeH
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.