Deserialize JSON using Entity Framework Core C#

Viewed 488

Basically, i want to get(deserialize directly into objects) the data under "rows" property of below JSON.

What wrapper classes do i need to create so that i can directly use JsonConvert.DeserializeObject<'SomeWrapperClass'>(message); to get this data "rows": [ [ 19.545363672276512, "JapanUnifia-Trial", 20180331, "USD" ], [ 173.41979241290323, "RVIIOT-TRIAL", 20180331, "USD" ], [ 20.359416562625452, "VSTSHOL-1595322048000", 20180331, "USD" ] ] as an Array of some objects which can be persisted in DB using EF Core.

{
  "id": "providers/Microsoft.Billing/billingAccounts/70664866/enrollmentAccounts/456/providers/Microsoft.CostManagement/Query/ad67fd91-c131-4bda-9ba9-7187ecb1cebd",
  "name": "ad67fd91-c131-4bda-9ba9-7187ecb1cebd",
  "type": "microsoft.costmanagement/Query",
  "properties": {
    "nextLink": "https://management.azure.com/providers/Microsoft.Billing/billingAccounts/70664866/enrollmentAccounts/456/providers/Microsoft.CostManagement/Query?api-version=2019-10-01&$skiptoken=AQAAAA%3D%3D",
    "columns": [
      {
        "name": "PreTaxCost",
        "type": "Number"
      },
      {
        "name": "ResourceGroup",
        "type": "String"
      },
      {
        "name": "UsageDate",
        "type": "Number"
      },
      {
        "name": "Currency",
        "type": "String"
      }
    ],
    "rows": [
      [
        19.545363672276512,
        "JapanUnifia-Trial",
        20180331,
        "USD"
      ],
      [
        173.41979241290323,
        "RVIIOT-TRIAL",
        20180331,
        "USD"
      ],
      [
        20.359416562625452,
        "VSTSHOL-1595322048000",
        20180331,
        "USD"
      ]
    ]
  }
}

This sample json taken from https://docs.microsoft.com/en-us/rest/api/cost-management/query/usage

1 Answers

Here are the classes to get the rows property:

public class Properties
{
    public List<List<object>> rows { get; set; }
}

public class Root
{
    public Properties properties { get; set; }
}

Then Deserialize with Newtonsoft.Json:

var values = JsonConvert.DeserializeObject<Root>(message).properties.rows;

And to use this data in a db, have your model class:

public class dbModel
{
    public double propertyName { get; set; }
    // Add other properties

    //With the name of db model and view model being valid table names
    //the properties being of the same data types as values.rows
}

And a View Model class:

public class dbViewModel
{
    public IEnumerable<dbModel> dbModels { get; set; }

    //Use this class to Enumerate through the rows
}
Related