【问题标题】:Design for car generator object汽车发电机对象设计
【发布时间】:2019-05-17 17:30:24
【问题描述】:

我正在做一个 .NET Core 教程,但我在理解练习方面遇到了麻烦。我有一个简单的页面,其中包含用于将新车添加到数据库的表单。用户点击“添加新车”,当他必须提供时加载表格:车身样式(下拉列表)、颜色、V-max、变速箱类型(下拉列表)、门数和 VIN 号,然后点击“保存” " 并且汽车被添加到数据库中。它已经完成并且工作正常。

现在我必须对其进行一些更改,因此在单击“添加新车”下拉菜单后显示可能的汽车类型,用户选择特定的汽车类型,然后加载与以前相同的表单,但根据配置预填充数据文件。

练习如下: a) 创建 JSON 配置文件,其中包含特定汽车类型的预定义设置(它不必包含所有设置), b) 提出汽车发电机对象的设计。

虽然我对 a) 点没有任何问题,但我在 b) 点上苦苦挣扎,只是因为……我不明白。我的配置文件示例如下所示:

[
 {
  "Body style": "Kombi",
  "Color": "Red",
  "V-max": 240,
  "Gearbox type": "Manual"
 },
 {
  "Body style": "Sedan",
  "Color": "Blue",
  "Number of doors": 5,
  "VIN number": "SomeVIN123"
 }
] 

我现在该怎么办?我知道我必须创建一些类来处理从 JSON 文件读取的数据以便将其传递给表单,但是“汽车发电机对象的设计”是怎么回事?

只是我应该准备这门课吗?像这样?

 public class CarType
 {
     public string bodyStyle { get; set; }
     public string Color { get; set; }
     public int vMax { get; set; }
     public string gearboxType { get; set; }
     public int doorsNumber { get; set; }
     public string vinNumber { get; set; }
 }

【问题讨论】:

    标签: c# json object asp.net-core


    【解决方案1】:

    你需要创建另一个类:

     public class CarTypeEntity
         {
            [JsonProperty("Cars")]
            public List<CarType> Cars { get; set; }
         }
    
    public class CarType
     {
         [JsonProperty("Body style")]
         public string bodyStyle { get; set; }
    
         [JsonProperty("Color")]
         public string Color { get; set; }
    
         [JsonProperty("V-max")]
         public int vMax { get; set; }
    
         [JsonProperty("Gearbox type")]
         public string gearboxType { get; set; }
    
         [JsonProperty("Number of doors")]
         public int doorsNumber { get; set; }
    
         [JsonProperty("VIN number")]
         public string vinNumber { get; set; }
     }
    

    去现实化

    CarTypeEntity result = JsonConvert.DeserializeObject<CarTypeEntity>(yourString);
    

    你的字符串是这样的:

    'Cars': [
     {
      "Body style": "Kombi",
      "Color": "Red",
      "V-max": 240,
      "Gearbox type": "Manual"
     },
     {
      "Body style": "Sedan",
      "Color": "Blue",
      "Number of doors": 5,
      "VIN number": "SomeVIN123"
     }
    ]
    

    【讨论】:

    • 那么我对练习“b)”的理解正确吗?我所要做的只是将 JSON 配置文件反序列化到类中?
    • 这将为您提供一个列表,其中包含您的所有设置
    猜你喜欢
    • 1970-01-01
    • 2017-02-20
    • 1970-01-01
    • 1970-01-01
    • 2013-11-04
    • 2020-11-14
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    相关资源
    最近更新 更多