0

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?

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
FIN WIN
  • 33
  • 8
  • Please refer [THIS](https://stackoverflow.com/questions/48214807/unexpected-json-token-when-reading-datatable-expected-startarray-got-startobje) – Shawn Xiao May 25 '20 at 07:49
  • 1
    Where did the `"data"` key come from? The dataset is inside the object bound to that key, you need to deserialize your json into a root object with a Data property of type DataSet. – Lasse V. Karlsen May 25 '20 at 08:23

1 Answers1

1

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

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300