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

时间:2017-12-30 23:12:48

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

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

GravitySnapHelper(Gravity.START).attachToRecyclerView(recyclerview);

我有这些模型类:

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

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

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

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

但是... // 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); 总是返回null,所以它没有得到正确的反序列化。

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

1 个答案:

答案 0 :(得分:3)

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