Search code examples
c#jsondatatablejson.netjson-deserialization

Get error when deserialize JSON object to DataTable


My code is:

DataTable dsAcknowledgement = new DataTable();               
int Count = 1;

dsAcknowledgement = JsonConvert.DeserializeObject<DataTable>(Convert.ToString(Input));
foreach (DataRow dr in dsAcknowledgement.Rows)
{
    string encrypteddata = Convert.ToString(dr["url"]);
    string DecrypteUrl = SbntAPICrypto.Decrypt(Encrypt_AES256_Key, Encrypt_AES256_iv,         encrypteddata);
    Count++;
}

Input = JsonConvert.SerializeObject(dsAcknowledgement);
return ShipmateWebService(Input);

I get the following error:

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

How to convert this JSON object to DataTable?

{
  "ServiceName": "Fileabcdssss",
  "origin": "abc",
  "Data": [
    {
      "status": 200,
      "statusMessage": "success",
      "url": "FILE_URL"
    },
    {
      "status": 200,
      "statusMessage": "success",
      "url": "FILE1_URL"
    }
  ]
}

Solution

  • Your JSON is an object but not an array. And deserialize to DataTable requires a JSON array.

    Assume that you are trying to extract the Data array from the JSON object, you should extract as below:

    using Newtonsoft.Json.Linq;
    
    dsAcknowledgement = JObject.Parse(Convert.ToString(Input))
                .SelectToken("Data")
                .ToObject<DataTable>();