Skip to main content
 首页 » 编程设计

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

2024年02月25日38lori

我的应用程序正在使用一个 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,所以它没有被正确反序列化。

有没有办法让我更改我的 View 模型,以便我可以正确反序列化 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 格式不正确。