Steven
Steven

Reputation: 18869

Deserializing a collection of objects with dynamic keys

My application is consuming an API, and I'm trying to deserialize data coming back. The data is formatted like:

{
  "1000!%abc":{
    "listingID":"1000"
    "zipcode":"87654",
    "address":"123 Main St",
    "streetNumber":"123",
    "streetName":"Main St",
    "latitude":-22.04666 
    "longitude":-32.65537,
  },
  "2000!%abc":{
    "listingID":"2000"
    "zipcode":"45678",
    "address":"345 Main St",
    "streetNumber":"345",
    "streetName":"Main St",
    "latitude":-22.04666 
    "longitude":-32.65537,
  }
}

I have these model classes:

public class PropertyListViewModel
{
    public List<PropertyViewModel> Properties { get; set; }
}

public class PropertyViewModel
{
    [JsonProperty("listingID")]
    public int ListingId { get; set; }
}

I'm just trying to get the listingID right now to try and make sure it's working

... // create HttpClient object, add headers and such
System.Net.Http.HttpResponseMessage response = await client.GetAsync(endpointUrl);
var jsonString = response.Content.ReadAsStringAsync();
PropertyListViewModel model = 
    JsonConvert.DeserializeObject<PropertyListViewModel>(jsonString.Result);

But model always comes back at null, so it's not getting deserializied correctly.

Is there a way for me to change my view models so that I can deserialize the json correctly?

Upvotes: 1

Views: 693

Answers (1)

Nkosi
Nkosi

Reputation: 247591

Use a Dictionary<string, PropertyViewModel> to represent the property list model.

assuming...

public class PropertyViewModel {
    public string ListingID { get; set; }
    public string Zipcode { get; set; }
    public string Address { get; set; }
    public string StreetNumber { get; set; }
    public string StreetName { get; set; }
    public double Latitude { get; set; }
    public double Longitude { get; set; }
}

From there

var response = await client.GetAsync(endpointUrl);
var jsonString = await response.Content.ReadAsStringAsync();
var propertyList = JsonConvert.DeserializeObject<Dictionary<string, PropertyViewModel>>(jsonString);
var property = propertyList["1000!%abc"];

Note how ever that the example JSON provided is not well formatted as commas are missing.

Upvotes: 3

Related Questions