WebAPI返回不带根节点的JSON数组 [英] WebAPI Return JSON array without root node

查看:198
本文介绍了WebAPI返回不带根节点的JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在EmployeeController中有以下示例代码,该代码创建了几个雇员,将它们添加到雇员列表中,然后在get请求中返回该雇员列表.从代码返回的JSON包含Employees作为根节点.我需要返回一个没有Employees属性的JSON数组,因为每当我尝试将JSON结果解析为对象时,除非手动将字符串重新格式化为不包含该字符串,否则都会收到错误消息.

I have the following sample code in an EmployeeController that creates a couple of employees, adds them to an employee list, and then returns the employee list on a get request. The returned JSON from the code includes Employees as a root node. I need to return a JSON array without the Employees property because whenever I try to parsethe JSON result to objects I get errors unless I manually reformat the string to not include it.

public class Employee
{
    public int EmployeeID { get; set; }
    public string Name { get; set; }
    public string Position { get; set; }
}

public class EmployeeList
{
    public EmployeeList()
    {
        Employees = new List<Employee>();
    }
    public List<Employee> Employees { get; set; }
}


public class EmployeeController : ApiController
{
    public EmployeeList Get()
    {
        EmployeeList empList = new EmployeeList();
        Employee e1 = new Employee
        {
            EmployeeID = 1,
            Name = "John",
            Position = "CEO"
        };
        empList.Employees.Add(e1);
        Employee e2 = new Employee
        {
            EmployeeID = 2,
            Name = "Jason",
            Position = "CFO"
        };
        empList.Employees.Add(e2);

        return empList;
    }
}

这是我在调用控制器

{
    "Employees":
        [
           {"EmployeeID":1,"Name":"John","Position":"CEO"},     
           {"EmployeeID":2,"Name":"Jason","Position":"CFO"}
        ]
}

这是我需要返回的JSON结果

This is the JSON result that I need returned

[
    {"EmployeeID":1,"Name":"John","Position":"CEO"},     
    {"EmployeeID":2,"Name":"Jason","Position":"CFO"}
]

由于我是WEBAPI的新成员并解析JSON结果,因此非常感谢任何帮助

Any help is much appreciated as I am new to WEBAPI and parsing the JSON results

推荐答案

之所以会发生这种情况,是因为您实际上没有返回List<Employee>,而是返回其中包含List<Employee>的对象(EmployeeList).
将其更改为返回Employee[](Employee的数组)或仅List<Employee>而不包含类

That happens because you are not actually returning a List<Employee> but an object (EmployeeList) that has a List<Employee> in it.
Change that to return Employee[] (an array of Employee) or a mere List<Employee> without the class surrounding it

这篇关于WebAPI返回不带根节点的JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆