Deserialize Json into object of type T returns 0

寵の児 提交于 2020-01-16 04:14:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!