问题
I'm trying to deserialize the JSON response to List, it always returns 0. Please look at the code below and suggest the fix.
JSON Data:-
tripSeats = {"seats":[
{"available":"true","baseFare":"600","serviceTaxAbsolute":"0"},
{"available":"true","baseFare":"600","serviceTaxAbsolute":"0"}
]}
My Classes:-
public class Seat
{
public string available { get; set; }
public string baseFare { get; set; }
public string serviceTaxAbsolute { get; set; }
}
public class Seats
{
public List<Seat> seats { get; set; }
}
Now i'm trying to Deserialize the JSON data and store it in List object as given below
JavaScriptSerializer ser = new JavaScriptSerializer();
List<Seats> seats = ser.Deserialize<List<Seats>>(tripSeats.ToString());
It does nothing, when I debug the code I see seats has 0.
回答1:
The problem is you're attempting to deserialize a Seats
object into a List<Seats>>
.
You either need to change it to a List<Seat>
or simply use Seats
:
JavaScriptSerializer ser = new JavaScriptSerializer();
Seats seats = ser.Deserialize<Seats>(tripSeats);
or
JavaScriptSerializer ser = new JavaScriptSerializer();
List<Seat> seats = ser.Deserialize<List<Seat>>(tripSeats);
回答2:
Try something like this:
public class Seat
{
public string available { get; set; }
public string baseFare { get; set; }
public string serviceTaxAbsolute { get; set; }
public Seat() { }
}
string text = "[{\"available\":\"true\",\"baseFare\":\"600\",\"serviceTaxAbsolute\":\"0\"},{\"available\":\"true\",\"baseFare\":\"600\",\"serviceTaxAbsolute\":\"0\"}]";
List<Seat> seats = new List<Seat>();
public MainPage()
{
this.InitializeComponent();
seats = JsonConvert.DeserializeObject<List<Seat>>(text);
}
来源:https://stackoverflow.com/questions/25483074/deserialize-json-into-object-of-type-t-returns-0