Home > Software engineering >  C# convert model object to Datatable
C# convert model object to Datatable

Time:09-16

I have a .Net application which is calling a WebAPI

The WebApi response is a JsonString:

{
     "total" : 50,
     "users" : [
         {
            "id" : "abc123",
            "firstName" : "First1",
            "lastName" : "Last1",
            "roles" : [
                 "admin"
             ]
         },
         {
            "id" : "abc124",
            "firstName" : "First2",
            "lastName" : "Last2",
            "roles" : [
                 "admin",
                 "normal"
             ]
         },
         ...... so on
      ]
 }
     

This is my model classes:

public class ApiResponse
{
     public int total { get; set; }
     public List<Users> users { get; set; }
     public ApiResponse()
     {
          users = new List<Users>();
     }
}

public class Users
{
     public string id { get; set; }
     public string firstName { get; set; }
     public string lastName{ get; set; }
     public List<string> roles { get; set; } 
}

I am converting the JsonString response from web api to my model object:

 var response = myObj.CallRestAPI("url");
 ApiResponse data = (ApiResponse)JsonConvert.DeserializeObject(response, typeOf(ApiResponse));

How do I convert this model object data to datatable to like below: -- to save in SQL database

id      firstName    lastName    roles
abc123  first1       last1       admin
abc124  first2       last2       admin, normal  

or is there a way to convert the jsonString directly to datatable?

I tried to convert the jsonString to Datatable:

JObject jObj = JObject.Parse(response);
DataTable dt = jObject["users"].ToObject<DataTable>();

But the resulting datatable is :

id      firstName    lastName    roles
abc123  first1       last1       **System.String[]**
abc124  first2       last2       **System.String[]**

CodePudding user response:

Using the same code you have, you could add another column:

    public class Users
    {
        public string id { get; set; }
        public string firstName { get; set; }
        public string lastName { get; set; }
        [JsonPropertyName("roles")] //put this attribute to bind this with roles from json
        public List<string> listRoles { get; set; }
        [JsonIgnore]  //to ignore this property coming from the json
        public string roles //add this new calculate column
        {
            get
            {
                return string.Join(',',listRoles);
            }
        }
    }

In the code, listRoles will contain the data converted from the json string into the Users class, then you will have an extra column roles that column will cotain the list of listRoles separate by ',', and I think you can remove the column listRoles from the resulting DataTable

Update: This is to generate the data you need for your table, next you can convert List to DataTable you can check this response for that: Convert list to datatable

CodePudding user response:

you have to parse your json at first

var usersParsed = JObject.Parse(response)["users"];
    
    //flatten roles to a string
    foreach (var item in usersParsed)
        item["roles"] = string.Join(",", item["roles"].ToObject<string[]>());


    DataTable dataTable = usersParsed.ToObject<DataTable>();
  • Related