Click here to Skip to main content
15,742,477 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:

I have a requirement to get some data from db using WebAPI and send back to user as a JSON string and convert back it to a datatable. I could not find out what is going wrong. Please suggest.

JSON string
"[{\"TestID\":\"1 \",\"WorkOrderID\":\"2 \",\"Recipe\":\"1110 \",\"FitCoeffA\":\"0 \",\"FitCoeffB\":\"0 \",\"FitCoeffC\":\"0 \",\"Temp0\":\"0 \",\"Temp1\":\"0 \",\"Temp2\":\"0 \",\"TestResult\":\"1 \"},{\"TestID\":\"1 \",\"WorkOrderID\":\"2 \",\"Recipe\":\"1110 \",\"FitCoeffA\":\"0 \",\"FitCoeffB\":\"0 \",\"FitCoeffC\":\"0 \",\"Temp0\":\"0 \",\"Temp1\":\"0 \",\"Temp2\":\"0 \",\"TestResult\":\"1 \"}]"

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

Error stack trace

at Newtonsoft.Json.Converters.DataTableConverter.ReadJson(JsonReader reader, Type objectType, Object existingValue, JsonSerializer serializer)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.DeserializeConvertable(JsonConverter converter, JsonReader reader, Type objectType, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type)
at iMFCTest.Service.iMFCDAL.<getcalibrationdata>d__3.MoveNext() in C:\Users\20063692\source\Workspaces\E-07430-01-01\Solution\iMFCTest\iMFCTest.Service\iMFCDAL.cs:line 61

What I have tried:

I used below code for conversion:
DataTable table=(DataTable)JsonConvert.DeserializeObject(dataString, (typeof(DataTable)));
Updated 24-May-23 23:17pm

1 solution

I have checked and found no issue. Can you please check what JSON you are actually getting and validate it using JSONLint whether json is valid or not? Because the json you mentioned is correct and i was able to convert it into datatable. Check what the json you are exactly getting and validate it.

Check my code:

string s = "[{\"TestID\":\"1 \",\"WorkOrderID\":\"2 \",\"Recipe\":\"1110 \",\"FitCoeffA\":\"0 \",\"FitCoeffB\":\"0 \",\"FitCoeffC\":\"0 \",\"Temp0\":\"0 \",\"Temp1\":\"0 \",\"Temp2\":\"0 \",\"TestResult\":\"1 \"},{\"TestID\":\"1 \",\"WorkOrderID\":\"2 \",\"Recipe\":\"1110 \",\"FitCoeffA\":\"0 \",\"FitCoeffB\":\"0 \",\"FitCoeffC\":\"0 \",\"Temp0\":\"0 \",\"Temp1\":\"0 \",\"Temp2\":\"0 \",\"TestResult\":\"1 \"}]";

DataTable table = (DataTable)JsonConvert.DeserializeObject(s, (typeof(DataTable)));
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900