简体   繁体   中英

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:

Unexpected JSON token when reading DataTable. Expected StartArray, got StartObject. Path 'data', line 1, position 9.

from the DataSet dataSet = (DataSet)JsonConvert.DeserializeObject(json, (typeof(DataSet))); line.

The JSON response from server looks fine; 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:

{
  "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 . In particular, the DataSet data appears to be wrapped in an outer object. Try deserializing the JSON like this instead:

DataSet dataSet = JObject.Parse(json)["data"].ToObject<DataSet>();

Fiddle: https://dotnetfiddle.net/aOiaeH

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM