Reputation: 2551
I am trying to convert a json object to DataTable
using this method:
string jsonString="{"data":[{"uid":502458330,"name":"Mustapha Malass","pic_square":"https://fbcdn-profile-a.akamaihd.net/hprofile-ak-prn2/t5/276351_502458330_1748214131_q.jpg","online_presence":"idle"},"
DataTable obj = JsonConvert.DeserializeObject<DataTable>(jsonString.ToString());
but I get an error:
Additional text found in JSON string after finishing deserializing object.
PS: I didn't post all my json string because it's too big as you can see the ,
in the end wish point that the json is not complete.
Upvotes: 2
Views: 13970
Reputation: 4288
This isn't the most efficient but you could just loop over your JSON if it's not nested and create the DataTable. I wrote this in VB.Net and used a converter to switch it to C# (I came across this question when I was trying to do the same thing and the common snippits weren't working for me). Old question but I thought I'd share for posterity:
public static DataTable JsonToDataTable(string json, string tableName)
{
bool columnsCreated = false;
DataTable dt = new DataTable(tableName);
Newtonsoft.Json.Linq.JObject root = Newtonsoft.Json.Linq.JObject.Parse(json);
Newtonsoft.Json.Linq.JArray items = (Newtonsoft.Json.Linq.JArray)root[tableName];
Newtonsoft.Json.Linq.JObject item = default(Newtonsoft.Json.Linq.JObject);
Newtonsoft.Json.Linq.JToken jtoken = default(Newtonsoft.Json.Linq.JToken);
for (int i = 0; i <= items.Count - 1; i++)
{
// Create the columns once
if (columnsCreated == false)
{
item = (Newtonsoft.Json.Linq.JObject)items[i];
jtoken = item.First;
while (jtoken != null)
{
dt.Columns.Add(new DataColumn(((Newtonsoft.Json.Linq.JProperty)jtoken).Name.ToString()));
jtoken = jtoken.Next;
}
columnsCreated = true;
}
// Add each of the columns into a new row then put that new row into the DataTable
item = (Newtonsoft.Json.Linq.JObject)items[i];
jtoken = item.First;
// Create the new row, put the values into the columns then add the row to the DataTable
DataRow dr = dt.NewRow();
while (jtoken != null)
{
dr[((Newtonsoft.Json.Linq.JProperty)jtoken).Name.ToString()] = ((Newtonsoft.Json.Linq.JProperty)jtoken).Value.ToString();
jtoken = jtoken.Next;
}
dt.Rows.Add(dr);
}
return dt;
}
http://www.blakepell.com/convert-json-to-a-datatable-with-c-or-vb-net
Upvotes: 1
Reputation: 11793
Try this code .
String json="....some json string...";
DataTable tester = (DataTable) JsonConvert.DeserializeObject(json, (typeof(DataTable)));
It works for me.
And try to search in the google first time when you have problem like this. Trust me ,you are not the only one who got the same problem.
Upvotes: 5