I want to generically flatten some json so I can convert to a datatable and bind to a datagrid using c#
What is the best way of doign it, bearing in mind I dont know
Deserialize, then LINQ select to flatten. I'm guessing, since you haven't stated it, that you want all the appointment and installer information on the same record as the specific installation?
My initial idea would be to leverage dynamics so that you can avoid having to put in static schemas for your JSON. If you already have static types that can act as JSON schemas, then you can avoid dynamics (and all that it entails). Here's an example class - using JSON.NET - to illustrate what I'm thinking:
public class DeserializeAndFlatten
{
public dynamic ParseJson()
{
var appointment = JObject.Parse(JsonData.JSON_TO_PARSE); // <-- replace the constant w/ the real JSON...
// this is where you flatten it all out!
// not going to put all the fields in, that would kill the example, LOL
var installations = appointment["installations"].Select(installation => new
{
appointmentId = appointment["appointmentid"],
policyId = appointment["policyid"],
vehicleId = appointment["vehicle"]["id"],
vehicleMake = appointment["vehicle"]["make"],
vehicleModel = appointment["vehicle"]["model"],
installerId = appointment["installer"]["installerid"],
installerName = appointment["installer"]["name"],
installationId = installation["installationid"],
installationStatus = installation["installationstatus"]["installationstatus"],
installationStatusId = installation["installationstatus"]["installationstatusid"],
}).ToList();
return installations;
}
}
You can test the code:
static void Main(string[] args)
{
var jsonParser = new DeserializeAndFlatten();
var installations = jsonParser.ParseJson();
// FYI we get back a dynamic listing,
// so intellisense wont work...
foreach (var installation in installations)
{
Console.WriteLine($"appointmentId: {installation.appointmentId}");
Console.WriteLine($"installer: {installation.installerName}");
Console.WriteLine($"installation id: {installation.installationId}");
Console.WriteLine($"status: {installation.installationStatus}");
Console.WriteLine();
}
Console.ReadLine();
}