I extract JSON code from an API
There is no problem with that
the JSON output is this string
\"[\\r\\n {\\r\\n \\\"PtsID\\\": 14061\\r\\n }\\r\\n]\"
but when I try to convert this to a datatable
using this line of code
Here is my code
DataTable dt1 = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable)));
I get this error
Newtonsoft.Json.JsonSerializationException: 'Unexpected JSON token when reading DataTable. Expected StartArray, got String. Path '', line 1, position 46.'
I tried analysing the json string but no luck finding what could cause this error!!!
here is my code
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
string json = client.GetStringAsync(url).Result;
DataTable dt1 = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable)));
Edit
I looked at this answer here
Deserialize a nested DataSet from Json String with Json.NET
and changed my code to this
class MyTableUtilClass
{
public string PtsID { get; set; }
public DataTable Table { get; set; }
}
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
string json = client.GetStringAsync(url).Result;
var myUtil = JsonConvert.DeserializeObject<MyTableUtilClass>(json);
DataTable myTable = myUtil.Table;
but when reach this line
var myUtil = JsonConvert.DeserializeObject<MyTableUtilClass>(json);
I get this error
Newtonsoft.Json.JsonSerializationException: 'Error converting value "[ { "PtsID": 14061 } ]" to type 'Encoder.FrmCoder+MyTableUtilClass'. Path '', line 1, position 46.'
which is the same error i got before..
any solution?
Edit
In the API I convert a datatable into JSON
so I can convert the JSON back to datatable in the application
Here is the code from the API
[Route("api/SearchSelect")]
public string Get(string P1 = null, string P2 = null, string P3 = null, string P4 = null)
{
SqlConnection conn = new SqlConnection(gDBConn);
SqlCommand cmd = new SqlCommand("SearchSelect", conn);
cmd.CommandTimeout = 0;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@PtsName", P1));
cmd.Parameters.Add(new SqlParameter("@PtsNo", P2));
cmd.Parameters.Add(new SqlParameter("@RepCode", P3));
cmd.Parameters.Add(new SqlParameter("@RepText", P4));
try
{
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
var dt = new DataTable();
dt.Load(rdr);
List<DataRow> result = dt.AsEnumerable().ToList();
rdr.Close();
string json = DataTableToJSON(dt);
return json;
}
catch (Exception ex)
{
return ex.Message;
}
}
public string DataTableToJSON(DataTable dt)
{
string JSONString = string.Empty;
string json = JsonConvert.SerializeObject(dt, Formatting.Indented);
return json;
}