Search code examples
c#asp.netjsonwebapi

Additional text found in JSON string after finishing deserializing object in api call


I have an api response which I want to convert into Datatable, so for that I write the below code.

inputJsonIPColoMaster = (new JavaScriptSerializer()).Serialize(inputIPColoMaster);

                                WebClient client = new WebClient();
                                client.Headers["Content-type"] = "application/json";
                                client.Encoding = Encoding.UTF8;
                                json = client.UploadString(apiUrl, inputJsonIPColoMaster);
                                DataTable dtRes = new DataTable();
                                
                                StringReader sr = new StringReader(json);
                                dtRes = JsonConvert.DeserializeObject<DataTable>(json); // here is the error

So while DeSerializing it I am getting error as.

Additional text found in JSON string....

Below is my response.

{"Status":"Failed","Code":"400","Message":"Request initiation failed"}

Solution

  • If you would like to show the response on a data grid view, here is how you can achieve it:

    (P.S: I have seen your other question as well - Assign var values in a datatable c#)

    var list = new List<ApiResponseModel>();
    var json = "{\"Status\":\"Failed\",\"Code\":400,\"Message\":\"Request initiation failed\"}";
    var model = JsonConvert.DeserializeObject<ApiResponseModel>(json);
    model.Id = Guid.NewGuid(); //set NEID
    list.Add(model);
    
    dataGridView1.DataSource = list;
    

    ApiResponseModel.cs

    public class ApiResponseModel
    {
        public Guid Id { get; set; }
        public string Status { get; set; }
        public int Code { get; set; }
        public string Message { get; set; }
    }