2017-10-10 84 views
0

我有一個很大的json字符串,我想反序列化(在c#中)到一個對象圖。大多數情況下,這很好,除了我不知道如何映射的json的一部分。反序列化具有「動態」名稱的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

您可以使用這組類:

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);