简体   繁体   中英

how to datatable convert into json

i have following json code, there is any library and method that i used mydatatable values convert into json because i post the data json format. its very hard to add these type of parameter.

   using (var content = new StringContent("{  \"vehicles\": [    {      \"vehicle_type\": \""+ vehicale_type +"\",      \"vehicle_id\": \"" +vehicle_id+"\"," +
                   "\"vehicle_plate\": \"" +vehicle_plate+ "\",      \"latitude\": "+latitude +"+,      \"longitude\": "+longitude+",      \"eta_minutes\": null, " +
                   "\"make\": \"null\",      \"model\": \""+carModel+"\",      \"color\": \"Black\",      \"status\": \""+status+"\",  " +
                   "\"driver_id\": \"" + driver_id + "\",      \"driver_phone\": \"" + driver_phone + "\",      \"driver_first_name\": \"" + driver_first_name + "\",   " +
                   "\"driver_last_name\": \"" + driver_last_name + "\",      \"direction\": {        \"kph\": 20,        \"heading\": 90      }    },  " +
                   "{      \"vehicle_type\": \"" + vehicale_type2 + "\",      \"vehicle_id\": \""+vehicle_id2+"\",      \"vehicle_plate\": \""+vehicle_plate2+"\",      \"latitude\":"+latitude2+",  " +
                   "\"longitude\":" + longitude2 + ",      \"eta_minutes\": null,      \"make\": \"null\",      \"model\": \"" + carModel2+ "\",  " +
                   "\"color\": \"Black\",      \"status\": \""+status2+"\",      \"driver_id\": \""+driver_id2+"\",      \"driver_phone\": \""+driver_phone2+"\",   " +
                   "\"driver_first_name\": \"" + driver_first_name2+ "\",      \"driver_last_name\": \"" + driver_last_name2 + "\",      \"direction\": {        \"kph\": 20,     " +
                   "\"heading\": 90      }    }  ]}", System.Text.Encoding.Default, "application/json"))
               {
                   using (var response = await httpClient.PostAsync("{supplier_id}/availability?version=2", content))
                   {
                       string responseData = await response.Content.ReadAsStringAsync();
                   }
               }

Follow these steps to get this thing done in a very effective and better way:

  1. Create a class with required properties to be sent in request.

     //for example public class Request { public List<Vehicle> vehicles { get; set; } } public class Vehicle { public string vehicle_type {get; set;} } 
  2. Assign the values to the object

     Request request =new Request(); request.vehicles = new List<Vehicle>(); // and so on 
  3. Use Newtonsoft.Json to serialize the object as:

     var json = JsonConvert.SerializeObject(request); 
  4. Invoke your request with json

     using (var response = await httpClient.PostAsync("{supplier_id}/availability?version=2", json)) { string responseData = await response.Content.ReadAsStringAsync(); } 

This would help to formate your datatable values in json string. Pass your actual datatable object and method will return back string of json.

public string DataTableToJsonObj(DataTable dt)
{
    DataSet ds = new DataSet();
    ds.Merge(dt);
    StringBuilder JsonString = new StringBuilder();
    if (ds != null && ds.Tables[0].Rows.Count > 0)
    {
        JsonString.Append("[");
        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
        {
            JsonString.Append("{");
            for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
            {
                if (j < ds.Tables[0].Columns.Count - 1)
                {
                    JsonString.Append("\"" + ds.Tables[0].Columns[j].ColumnName.ToString() + "\":" + "\"" + ds.Tables[0].Rows[i][j].ToString() + "\",");
                }
                else if (j == ds.Tables[0].Columns.Count - 1)
                {
                    JsonString.Append("\"" + ds.Tables[0].Columns[j].ColumnName.ToString() + "\":" + "\"" + ds.Tables[0].Rows[i][j].ToString() + "\"");
                }
            }
            if (i == ds.Tables[0].Rows.Count - 1)
            {
                JsonString.Append("}");
            }
            else
            {
                JsonString.Append("},");
            }
        }
        JsonString.Append("]");
        return JsonString.ToString();
    }
    else
    {
        return null;
    }
}  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM