Here is My Code Sample:
string json = "[{Vehicle:BMW With Ethiraj,Date:30 Jul 2013 09:24 AM,Location:Hauz Khas Enclave New Delhi Delhi India, Speed:42}]";
by custom method
DataTable dt = JsonStringToDataTable(json);
by Newtonsoft method
DataSet ds = (DataSet)Newtonsoft.Json.JsonConvert.DeserializeObject(json);
JsonStringToDataTable method:-
public DataTable JsonStringToDataTable(string jsonString)
{
DataTable dt = new DataTable();
string[] jsonStringArray = Regex.Split(jsonString.Replace("[", "").Replace("]", ""), "},{");
List<string> ColumnsName = new List<string>();
foreach (string jSA in jsonStringArray)
{
string[] jsonStringData = Regex.Split(jSA.Replace("{", "").Replace("}", ""), ",");
foreach (string ColumnsNameData in jsonStringData)
{
try
{
int idx = ColumnsNameData.IndexOf(",");
string ColumnsNameString = ColumnsNameData.Substring(0, idx - 1).Replace("\"", "");
if (!ColumnsName.Contains(ColumnsNameString))
{
ColumnsName.Add(ColumnsNameString);
}
}
catch (Exception ex)
{
throw new Exception(string.Format("Error Parsing Column Name : {0}", ColumnsNameData));
}
}
break;
}
foreach (string AddColumnName in ColumnsName)
{
dt.Columns.Add(AddColumnName);
}
foreach (string jSA in jsonStringArray)
{
string[] RowData = Regex.Split(jSA.Replace("{", "").Replace("}", ""), ",");
DataRow nr = dt.NewRow();
foreach (string rowData in RowData)
{
try
{
int idx = rowData.IndexOf(":");
string RowColumns = rowData.Substring(0, idx - 1).Replace("\"", "");
string RowDataString = rowData.Substring(idx + 1).Replace("\"", "");
nr[RowColumns] = RowDataString;
}
catch (Exception ex)
{
continue;
}
}
dt.Rows.Add(nr);
}
return dt;
}
but above both method are throw error
Why i'm trying this JSON to Dataset means need to export excel, pdf, etc by Jquery client side Jquery ajax method we send JSON data and process at Web-method without depend c# code as well as i tried excel export using jquery method but which is not support Internet Explorer so thats why i try to do this DeserializeObject, so anybody have different idea pls share
You are getting the error with the Newtonsoft method because the json
string is not in correct format. You should put the values within single/double quotes in that json string after which your sample json
would look something like this:
string json = "{\"arr\":[{\"Vehicle\":\"BMW With Ethiraj\",\"Date\":\"30 Jul 2013 09:24 AM\",\"Location\":\"Hauz Khas Enclave New Delhi Delhi India\", \"Speed\":\"42\"}]}";
Thereafter, use the Newtonsoft method in the below way:
DataSet ds = Newtonsoft.Json.JsonConvert.DeserializeObject<DataSet>(json);
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.