1

This is a tough one: Basically I want to map a complex JSON object with a collection consisting of different but similar complex types into a C# model. This is a default JSON my ASP.NET Web API will receive:

{
   "Id": "000111222333",
   "Move": {
      "Address2": {
         "City": "CityName",
         "Street": "StreetName",
         "PostalCode": "4444",
         "HouseNumber": "4",
         "Country": "NLD",
         "IsInhabited": "true"
      },
      "Contracts": {
         "ElectricityContract": {
            "ContractId": "000000031",
            "ContractNumber": "00000011",
            "EANCode": "53123123123123",
            "StartDate": "2000-01-20",
            "EndDate": "2017-06-06",
            "IsBuildingComplex": "false",
            "ForceSingleTariff": "false"
         },
         "CableContract": {
            "ContractId": "456454546353",
            "ContractNumber": "12312312313",
            "StartDate": "2000-01-20",
            "EndDate": "2017-01-23"
         }
      }
   }
}

My problem here is that I can't seem to receive the different kinds of Contracts as a single collection.

I've tried to map the "Contracts" sequence to an ArrayList but its always 'null'. I've tried to map it to ICollection/IEnumerable/List< IContract> where all contracts are a type of IContract. But this doesn't work as well.

I've started to manually map from the JSON string, but I hope there's a better way to do this? All help appreciated.

srgskiri
  • 33
  • 7

1 Answers1

1

To get a Contracts collection inside this object you need to change your JSON to this one

{
...      
"Contracts": [
         {
            "ContractId": "000000031",
            "Type": "ElectricityContract",
            "ContractNumber": "00000011",
            "EANCode": "53123123123123",
            "StartDate": "2000-01-20",
            "EndDate": "2017-06-06",
            "IsBuildingComplex": "false",
            "ForceSingleTariff": "false"
         },
         {
            "ContractId": "456454546353",
            "Type" : "CableContract",
            "ContractNumber": "12312312313",
            "StartDate": "2000-01-20",
            "EndDate": "2017-01-23"
         }
      ]
}

So, Contracts will be a JSON collection not an object and you can map it by using custom binding to ICollection/IEnumerable/List<IContract>. This binding should create different IContract implementation according to Type property. How to do this - take a look at this post.

Community
  • 1
  • 1
Vasyl Zvarydchuk
  • 3,789
  • 26
  • 37
  • Oh wow, I still have a long way to go as a programmer. Now that you showed it to me how it works, this looks so logical. Thank you Vasyl. I'de vote u up, but I still have no reputation to do that yet. – srgskiri Jan 26 '17 at 07:53