小编Fra*_*ito的帖子

无法反序列化当前JSON对象,为什么?

我正在尝试使用WebApi使用以下代码从数据库中获取员工列表:这是我的客户端MVC应用程序的代码:

        string u = "http://localhost:1411/api/EmployeeAPI";
        Uri uri = new Uri(u);

        HttpClient httpClient = new HttpClient();

        Task<HttpResponseMessage> response = httpClient.GetAsync(uri);

        Task.WaitAll(response);

        HttpResponseMessage resposta = response.Result;

        var msg = resposta.Content.ReadAsStringAsync().Result;

        Employee[] employees = JsonConvert.DeserializeObject<Employee[]>(msg);

        return View(employees);
Run Code Online (Sandbox Code Playgroud)

这是我的WebAPI的代码:

    public IEnumerable<Employee> GetEmployees()
    {
        return db.Employees.AsEnumerable();
    }
Run Code Online (Sandbox Code Playgroud)

但是这个错误不断弹出,我不明白为什么:

无法将当前JSON对象(例如{“ name”:“ value”})反序列化为类型'DataAccess.Employee []',因为该类型需要JSON数组(例如[1,2,3])才能正确反序列化。要解决此错误,可以将JSON更改为JSON数组(例如[1,2,3]),也可以更改反序列化类型,使其成为普通的.NET类型(例如,不像整数这样的原始类型,也不像这样的集合类型。数组或列表),可以从JSON对象反序列化。还可以将JsonObjectAttribute添加到类型中,以强制其从JSON对象反序列化。路径“消息”,第1行,位置11。

我的员工班级:

namespace DataAccess
{
    using System;
    using System.Collections.Generic;

    public partial class Employee
    {
        public Employee()
        {
            this.Products = new HashSet<Product>();
        }

        public int EmployeeId { get; set; }
        public string Title { get; …
Run Code Online (Sandbox Code Playgroud)

c# serialization json asp.net-web-api

3
推荐指数
1
解决办法
1万
查看次数

标签 统计

asp.net-web-api ×1

c# ×1

json ×1

serialization ×1