无法在localhost中反序列化Json

时间:2018-04-02 14:39:01

标签: c# json serialization deserialization json-deserialization

我有一个应用程序,其中保留了一些虚拟数据:

 public class ValuesController : ApiController
{
    // GET api/values
    public string Get()
    {
        List<Cars> carslist = new List<Cars>();
        carslist.Add(new Cars { Id = "1", Color = "RED", CompanyName = "AUDI", Years = "1993", Model = "A4" });
        carslist.Add(new Cars { Id = "2", Color = "BLUE", CompanyName = "MERCEDES", Years = "1992", Model = "BENZ" });
        carslist.Add(new Cars { Id = "3", Color = "GREEN", CompanyName = "BMW", Years = "1990", Model = "C-CLASS" });
        carslist.Add(new Cars { Id = "4", Color = "YELLOW", CompanyName = "VOLKSWAGEN", Years = "1989", Model = "JETTA" });
        //return carslist;
        //JavaScriptSerializer jss = new JavaScriptSerializer();
        //string jsonstring = jss.Serialize(carslist);
        //return jsonstring;

        string JsonString = JsonConvert.SerializeObject(carslist);
        return JsonString;
    }

完成JSON格式化后,我从另一个应用程序请求此特定数据,并在那里反序列化,但它始终显示错误。我接受这些数据的代码如下:

public ActionResult Index()
    {

        Uri url = new Uri(@"http://localhost:51933/api/Values");
        WebRequest webRequest = WebRequest.Create(url);
        WebResponse response = webRequest.GetResponse();
        StreamReader streamReader = new StreamReader(response.GetResponseStream());
        string responseData = streamReader.ReadToEnd().Trim();

        var sdf = JsonConvert.DeserializeObject<List<Cars>>(responseData);

        return View();
    }

模型就像这样

    public class Cars
{
    public string Id { get; set; }
    public string CompanyName { get; set; }
    public string Model { get; set; }
    public string Years { get; set; }
    public string Color { get; set; }

}

public class ListOfCars
{
    public List<Cars> listofcars { get; set; }
}

我真的不理解,为什么反序列化没有发生。请帮帮我。

提前致谢。

这两个应用程序都在localhost上运行

这是错误:

Error

1 个答案:

答案 0 :(得分:0)

从错误的屏幕截图中我可以看到您正在尝试反序列化为ListOfCars类,而不是List<Cars>。将类型更改为List<Cars>