我试图反序列化对List的JSON响应,它总是返回0.请查看下面的代码并提出修复建议。
JSON数据: -
tripSeats = {"seats":[
{"available":"true","baseFare":"600","serviceTaxAbsolute":"0"},
{"available":"true","baseFare":"600","serviceTaxAbsolute":"0"}
]}
我的课程: -
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; }
}
现在我试图反序列化JSON数据并将其存储在List对象中,如下所示
JavaScriptSerializer ser = new JavaScriptSerializer();
List<Seats> seats = ser.Deserialize<List<Seats>>(tripSeats.ToString());
它什么也没做,当我调试代码时,我看到座位有0。
答案 0 :(得分:2)
问题是您是否正在尝试将Seats
对象反序列化为List<Seats>>
。
您需要将其更改为List<Seat>
或仅使用Seats
:
JavaScriptSerializer ser = new JavaScriptSerializer();
Seats seats = ser.Deserialize<Seats>(tripSeats);
或
JavaScriptSerializer ser = new JavaScriptSerializer();
List<Seat> seats = ser.Deserialize<List<Seat>>(tripSeats);
答案 1 :(得分:0)
尝试这样的事情:
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);
}