C# extract useful information from json string with redundant message and code
The json string has additional message as below,I'll extract the data part and convert it to DataTable via JObject,JToken,Jarray in NewtonSoft.Json.
{"code":0,"msg":"","data":[{"Id":1,"Name":"Fred","Age":33,"Title":"CEO"},{"Id":2,"Name":"Fred2","Age":34,"Title":"CFO"},{"Id":3,"Name":"Fred3","Age":35,"Title":"CTO"}]}
static DataTable ConvertJsonFileToDt(string jsonValue) { DataTable dt = new DataTable(); if(string.IsNullOrEmpty(jsonValue)) { return dt; } JObject jObj = JObject.Parse(jsonValue); JToken jTokenData = jObj["data"]; JArray srcArray = JArray.FromObject(jTokenData); JArray targetArray = new JArray(); foreach(JObject row in srcArray.Children<JObject>()) { var cleanRow = new JObject(); foreach(JProperty column in row.Properties()) { if(column.Value is JValue) { cleanRow.Add(column.Name, column.Value); } } targetArray.Add(cleanRow); } dt = JsonConvert.DeserializeObject<DataTable>(targetArray.ToString()); return dt; }
Or it is just a serialized json string which is far more easier.
[{"Name":"Fred1","Age":33,"Id":1},{"Name":"Fred2","Age":34,"Id":2},{"Name":"Fred3","Age":35,"Id":3}]
static void DynamicJson() { var obj = new[] { new {Name="Fred1",Age=33,Id=1}, new {Name="Fred2",Age=34,Id=2}, new {Name="Fred3",Age=35,Id=3} }; var jsonValue = JsonConvert.SerializeObject(obj); DataTable dt = JsonConvert.DeserializeObject<DataTable>(jsonValue); }