【问题标题】:Deserializing a collection of objects with dynamic keys使用动态键反序列化对象集合
【发布时间】:2017-12-30 23:12:47
【问题描述】:

我的应用程序正在使用 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&lt;string,YourObjectType&gt;
  • 2000!%abc 不是List&lt;T&gt; 的有效索引。

标签: c# asp.net json json.net


【解决方案1】:

使用Dictionary&lt;string, PropertyViewModel&gt; 表示属性列表模型。

假设...

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 格式不正确,因为缺少逗号。

【讨论】:

    猜你喜欢
    • 2020-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 2012-11-11
    相关资源
    最近更新 更多