繁体   English   中英

使用动态键反序列化对象集合

[英]Deserializing a collection of objects with dynamic keys

我的应用程序正在使用API​​,我正在尝试反序列化返回的数据。 数据格式如下:

{
  "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,
  }
}

我有这些模型类:

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

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

我只是想立即获取listingID以确保它正常工作

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

但是model总是返回null,所以它没有得到正确的反序列化。

有没有办法让我更改我的视图模型,以便我可以正确反序列化json?

使用Dictionary<string, PropertyViewModel>来表示属性列表模型。

假设...

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

从那里

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"];

请注意,提供的示例JSON如何格式不正确,因为缺少逗号。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM