xdzgor
xdzgor

Reputation: 61

deserialize json with "dynamic" names

I have a large json string, which I want to deserialize (in c#) to an object graph. For the most part this works fine, except one part of the json which I don't know how to map.

The json is an "infoResponse", which contains a list of "servicePoints", each of which contains a "deliveryAddress" and a list of "openingHours".

It is the "openingHours" which I am having trouble with. They contain a "day", and a set of "from" and "to" values - where these values have names like "from1", "from2", "from3" etc, depending on how many opening and closing times there are on the "day". How do I model this and deserialize it?

Here is some example 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"
          }
        ]
      }
    ]
  }
}

Thanks for any pointers.

Upvotes: 0

Views: 44

Answers (1)

Alexander Petrov
Alexander Petrov

Reputation: 14231

You can use this set of classes:

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

Code:

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

Upvotes: 1

Related Questions