用“动态”名称反序列化json

时间:2017-10-10 07:53:14

标签: c# json

我有一个大的json字符串,我想将其反序列化(在c#中)到对象图。在大多数情况下,这工作正常,除了json的一部分,我不知道如何映射。

json是一个“infoResponse”,其中包含一个“servicePoints”列表,每个列表都包含一个“deliveryAddress”和一个“openingHours”列表。

这是我遇到麻烦的“开放时间”。它们包含一个“日”和一组“从”和“到”值 - 其中这些值的名称类似于“from1”,“from2”,“from3”等,具体取决于打开和关闭时间的数量。那天”。我如何对其进行建模并对其进行反序列化?

以下是Json的一些示例:

{
  "infoResponse": {
    "servicePoints": [
      {
        "servicePointId": "1000",
        "name": "Postbox 1000",
        "deliveryAddress": {
          "streetName": "High Street",
          "streetNumber": "4",
          "postalCode": "BW 234",
          "city": "London",
          "countryCode": "UK"
        },
        "openingHours": [
          {
            "from1": "0900",
            "to1": "1200",
            "from2": "1400",
            "to2": "1700",
            "day": "MO"
          },
          {
            "from1": "0000",
            "to1": "2359",
            "day": "TU"
          },
          {
            "from1": "1000",
            "to1": "1300",
            "from2": "1800",
            "to2": "2000",
            "from3": "1200",
            "to3": "2359",
            "day": "WE"
          },
          {
            "from1": "0000",
            "to1": "2359",
            "day": "TH"
          },
          {
            "from1": "0000",
            "to1": "2359",
            "day": "FR"
          },
          {
            "from1": "0000",
            "to1": "2359",
            "day": "SA"
          },
          {
            "from1": "0000",
            "to1": "2359",
            "day": "SU"
          }
        ]
      }
    ]
  }
}

感谢您的任何指示。

1 个答案:

答案 0 :(得分:1)

您可以使用这组课程:

public class Rootobject
{
    public Inforesponse infoResponse { get; set; }
}

public class Inforesponse
{
    public Servicepoint[] servicePoints { get; set; }
}

public class Servicepoint
{
    public string servicePointId { get; set; }
    public string name { get; set; }
    public Deliveryaddress deliveryAddress { get; set; }
    public Dictionary<string, string>[] openingHours { get; set; }
}

public class Deliveryaddress
{
    public string streetName { get; set; }
    public string streetNumber { get; set; }
    public string postalCode { get; set; }
    public string city { get; set; }
    public string countryCode { get; set; }
}

代码:

var root = JsonConvert.DeserializeObject<Rootobject>(json);