C#将Json加载到继承的类中

时间:2018-08-13 12:27:56

标签: c# json class inheritance

我有一个C#类,我需要将JSON解析为它。

该班级有另一个班级的List<>

类结构是这样的。

public class OrderFund {
  public int OrderID { get; set; }
  public int BrokerID { get; set; }
  public string SettlementMethod { get; set; }
  public List<SettlementSap> SettlementsSap { get; set; }
}

public class SettlementSap {
  public string SapMonetaryAccountNo { get; set; }
  public string SapMonetaryAccountType { get; set; }
  public string SapMonetaryAccountOffice { get; set; }
}

我的JSON就是这样。

{
  "settlementMethod": "SAP",
  "BrokerID": 1,
  "OrderID": 1,
  "Settlements": [
    {
      "SapMonetaryAccountNo": "400245892464",
      "SapMonetaryAccountType": "CA",
      "SapMonetaryAccountOffice": "AR"
    }
  ]
}

我这样加载JSON文件...

static OrderFund LoadJson(string file) {
  string dire = Directory.GetCurrentDirectory();
  using (StreamReader r = new StreamReader(dire + "\\" + file)) {
    string json = r.ReadToEnd();
    OrderFund items = JsonConvert.DeserializeObject<OrderFund>(json);
    return items;
  }
}

数据可以很好地加载到OrderFun类中,但是OrderFund.SettlementsSap为空。 如何将Settlements加载到SettlementsSap中?

3 个答案:

答案 0 :(得分:3)

那是因为您已将字段SettlementsSap命名为,但您的Json字段称为Settlements ...

您可以重命名班级中的字段;

 public class OrderFund 
    {
        public int OrderID { get; set; }
        public int BrokerID { get; set; }
        public string SettlementMethod { get; set; }
        public List<SettlementSap> Settlements { get; set; }
    }

或添加一个[JsonProperty(“ Settlements”)]  像这样归因于该字段;

public class OrderFund 
{
    public int OrderID { get; set; }
    public int BrokerID { get; set; }
    public string SettlementMethod { get; set; }
    [JsonProperty("Settlements")] 
    public List<SettlementSap> SettlementsSap { get; set; }
}

答案 1 :(得分:2)

您只需使用Visual Studio的功能即可将json转换为模型类

转到:编辑->粘贴特殊->将JSON作为类粘贴

此功能创建的模型类将解决您的问题

因此,可见,您必须将SettlementsSap重命名为Settlements

        public class OrderFund
        {
            public string settlementMethod { get; set; }
            public int BrokerID { get; set; }
            public int OrderID { get; set; }
            public Settlement[] Settlements { get; set; }
        }

        public class Settlement
        {
            public string SapMonetaryAccountNo { get; set; }
            public string SapMonetaryAccountType { get; set; }
            public string SapMonetaryAccountOffice { get; set; }
        }

答案 2 :(得分:0)

问题出在命名上。在JSON中,名称为Settlements。但是在OrderFund的类定义中,它被命名为SettlementsSap