Below is the sample json
{
"Count": 185,
"Message": "Results returned successfully",
"SearchCriteria": "Make ID:474 | ModelYear:2016",
"Results": [{
"Make_ID": 474,
"Make_Name": "Honda",
"Model_ID": 1861,
"Model_Name": "i10",
"owners": [{
"name": "Balaji",
"address": [{
"city": "kcp",
"pincode": "12345"
}
]
}, {
"name": "Rajesh",
"address": [{
"city": "chennai",
"pincode": "12346"
}
]
}
]
}, {
"Make_ID": 475,
"Make_Name": "Honda",
"Model_ID": 1862,
"Model_Name": "i20",
"owners": [{
"name": "Vijay",
"address": [{
"city": "madurai",
"pincode": "12347"
}
]
}, {
"name": "Andrej",
"address": [{
"city": "Berlin",
"pincode": "12348"
}
]
}
]
}
]}
Below is the XML config to build data table (assume getting from user)
<DataTableConfig Name="CityInfo">
<Property Name="Make_ID" Path="Results[*].Make_ID"/>
<Property Name="Model_ID" Path="Results[*].Model_ID" />
<Property Name="owner" Path="Results[*].owners[*].name"/>
<Property Name="city" Path="Results[*].owners[*].address[*].city"/></DataTableConfig>
The expected result is as below
With the below code I am trying to parse the json and building the data table based on the config.
I am getting column values in separate row and not working as expected
string xmlConfig = File.ReadAllText(@"C:\Temp\xmlConfig.txt");
XmlSerializer serializer = new XmlSerializer(typeof(DataTableConfig));
StringReader stringReader = new StringReader(xmlConfig);
DataTableConfig config = (DataTableConfig)serializer.Deserialize(stringReader);
DataTable dataTable = new DataTable();
foreach (Property p in config.Property)
{
dataTable.Columns.Add(p.Name);
}
dataTable.Columns.Add("Path"); //can be removed after building the table
string jdata = File.ReadAllText(@"C:\Temp\json.txt");
JObject json = JObject.Parse(jdata);
foreach (Property p in config.Property)
{
var jTokens = json.SelectTokens(p.Path);
foreach (JToken token in jTokens)
{
string parentPath = token.Parent.Parent.Path;
string searchExpression = $"Path = '{parentPath}'";
DataRow[] foundRows = dataTable.Select(searchExpression);
if (foundRows.Count() > 0)
{
string value = token.Value<string>();
foundRows[0][p.Name] = value;
}
else
{
string value = token.Value<string>();
DataRow toInsert = dataTable.NewRow();
toInsert[p.Name] = value;
toInsert["Path"] = parentPath;
dataTable.Rows.Add(toInsert);
}
}
}
foreach (DataRow row in dataTable.Rows)
{
StringWriter sw = new System.IO.StringWriter();
foreach (DataColumn col in dataTable.Columns)
sw.Write(row[col].ToString() + "\t");
string output = sw.ToString();
Console.WriteLine(output);
}
Console.ReadLine();
Any hints/tips are much appreciated. Thanks.


