I'm fetching a list of entries in a BD with a GET request (I'm using RestSharp to make the request) and I want to deserialize the content of the response into a List.
The type of list elements is "Mileage":
public class Mileage
{
public int BranchId { get; set; }
public int RouteId { get; set; }
public int Travels { get; set; }
public int Monday { get; set; }
public int Tuesday { get; set; }
public int Wednesday { get; set; }
public int Thursday { get; set; }
public int Friday { get; set; }
public int Saturday { get; set; }
public int Sunday { get; set; }
}
And the response.Content is like this:
{
"TheoreticalMileages": [
{
"BranchId": 36,
"RouteId": 1860,
"Travels": 10,
"Monday": 132,
"Tuesday": 89,
"Wednesday": 92,
"Thursday": 104,
"Friday": 112,
"Saturday": 0,
"Sunday": 79
},
{
"BranchId": 7,
"RouteId": 2600,
"Travels": 12,
"Monday": 40,
"Tuesday": 30,
"Wednesday": 40,
"Thursday": 100,
"Friday": 121,
"Saturday": 130,
"Sunday": 0
},
{
"BranchId": 23,
"RouteId": 33,
"Travels": 8,
"Monday": 54,
"Tuesday": 50,
"Wednesday": 35,
"Thursday": 50,
"Friday": 67,
"Saturday": 32,
"Sunday": 30
}
],
"TotalRecords": 3
}
I'm using Newtonsoft JSON.NET to deserialize the object into a list of mileages. I've already tried to convert it to a List and an IEnumerable:
var mileages = JsonConvert.DeserializeObject<IEnumerable<Mileage>>(getAllResponse.Content);
But I get the same error with both types of collections: "Cannot deserialize the current json object because the type requires a json array[...]"
Is there a way to convert the object directly into a list? Thanks in advance.
答案 0 :(得分:4)
The JSON you're using isn't a list. It's an object. One of its properties happens to be a list. Something like this:
public class MileageContainer
{
public IEnumerable<Mileage> TheoreticalMileages { get; set; }
public int TotalRecords { get; set; }
}
Then you should be able to deserialize the JSON into that object:
JsonConvert.DeserializeObject<MileageContainer>(getAllResponse.Content);