Home > Software design >  Unable to Deserialize Json to Dataset or Datatable
Unable to Deserialize Json to Dataset or Datatable

Time:03-20

I am getting a JSON response from a http get, and I can't seem to deserialize it. Here is the code getting the json.

    HttpClient client = new();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    client.DefaultRequestHeaders.Add("Authorization", $"Bearer {AuthToken}");
    HttpContent result = client.GetAsync(addressUrl).Result.Content;
    var jsonString = await result.ReadAsStringAsync();

I've tried a couple ways to deserialize:

var table = JsonConvert.DeserializeObject<DataSet>(jsonString); Gives me: Newtonsoft.Json.JsonSerializationException: 'Unexpected JSON token when reading DataTable. Expected StartArray, got String. Path '['@odata.context']', line 1, position 129.'

DataTable dt = (DataTable)JsonConvert.DeserializeObject(jsonString, (typeof(DataTable))); Gives me: Newtonsoft.Json.JsonSerializationException: 'Unexpected JSON token when reading DataTable. Expected StartArray, got StartObject. Path '', line 1, position 1.'

I read a bunch of replies here and most of them said that the JSON wasn't well formed. I pasted the JSON into jsonlint and it says it's well formed. Here is what I have:

{
    "@odata.context": "https://<server>/odataservice/odata/view/$metadata#reason_code",
    "value": [{
        "id": "10",
        "reason": "Leasehold Improvements",
        "company_no": "123"
    }, {
        "id": "11",
        "reason": "Promotional Expense",
        "company_no": "123"
    }, {
        "id": "12",
        "reason": "Display Expense",
        "company_no": "123"
    }, {
        "id": "9",
        "reason": "Golf Tournament",
        "company_no": "123"
    }]
}

CodePudding user response:

Your json contains a collection and a header. You can convert to data table only a collection (value). So try this

var jsonParsed=JObject.Parse(jsonString);

DataTable dataTable = jsonParsed["value"].ToObject<DataTable>();
  • Related