首页 > 解决方案 > 使用 Entity Framework Core C# 反序列化 JSON

问题描述

基本上,我想获取(直接反序列化为对象)JSON 下面的“行”属性下的数据。

我需要创建哪些包装类,以便我可以直接使用 JsonConvert.DeserializeObject<'SomeWrapperClass'>(message);这些数据"rows": [ [ 19.545363672276512, "JapanUnifia-Trial", 20180331, "USD" ], [ 173.41979241290323, "RVIIOT-TRIAL", 20180331, "USD" ], [ 20.359416562625452, "VSTSHOL-1595322048000", 20180331, "USD" ] ]作为一些对象的数组来获取,这些对象可以使用 EF Core 保存在 DB 中。

{
  "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"
      ]
    ]
  }
}

此示例 json 取自https://docs.microsoft.com/en-us/rest/api/cost-management/query/usage

标签: c#jsonentity-frameworkentity-framework-core

解决方案


以下是获取rows属性的类:

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

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

然后DeserializeNewtonsoft.Json

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

并在数据库中使用这些数据,让你的模型类:

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
}

还有一个视图模型类:

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

    //Use this class to Enumerate through the rows
}

推荐阅读