【问题标题】:C# WebAPI return JSON dataC# WebAPI 返回 JSON 数据
【发布时间】:2019-05-18 07:00:45
【问题描述】:

我对 C# 完全陌生,我正在尝试学习 WebApi。我有DataAccess.csproj,其中包含List,如下所示:

using System;
using System.Collections.Generic;
using DataAccess.BO;

namespace DataAccess
{
    public class PersonDataAccess
    {
        #region Data
        private static readonly List<Person> Data = new List<Person>
        {
            new Person
            {
                Id = 8,
                GivenName = "Trinh",
                FamilyName = "Montejano",
                BossId = 3,
                Title = "Tech Manager",
                Gender = Gender.Unspecified,
                DateOfBirth = DateTime.Parse("1966-09-27")
            },
            new Person
            {
                Id = 1,
                GivenName = "Winfred",
                FamilyName = "Fetzer",
                BossId = null,
                Title = "CEO",
                Gender = Gender.Unspecified,
                DateOfBirth = DateTime.Parse("1927-01-29")
            },
            new Person
            {
                Id = 2,
                GivenName = "Erich",
                FamilyName = "Dandrea",
                BossId = 1,
                Title = "VP of Marketing",
                Gender = Gender.Male,
                DateOfBirth = DateTime.Parse("1927-08-20")
            },
        };
#endregion

        //TODO:  Implement whatever methods are needed to access the data.
    }
}

我想以原始 JSON 格式返回数据,例如

{
    "User": {
        "Id" : "1",
        "FirstName" : "Winfred",
        "LastName" : "Fetzer",
        "BossName" : null,
        "Title" : "CEO",
        "DateOfBirth" : "1927-01-29",
        "Gender" : "Female",
        "Addresses" : [{
            "Id" : 1,
            "Street" :  "62 Durham Court",
            "City" : "Garfield",
            "State" : "NJ",
            "Zip" : "07026"
        },{
            "Id" : 2,
            "Street" :  "179 Cambridge Court",
            "City" : "Chippewa Falls",
            "State" : "WI",
            "Zip" : "54729"
        },{
            "Id" : 3,
            "Street" :  "573 Route 5",
            "City" : "Memphis",
            "State" : "TN",
            "ZipCode" : "38106"
        }]
    }
}

“地址”对象类似于PersonDataAccess

我的UserContrller.cs是这个

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using DataAccess;

namespace SrEngineer.Controllers
{
    [RoutePrefix("api/v1/user")]
    public class UserController : ApiController
    {

    }

}

所以,到目前为止,我只能弄清楚这一点,如何通过用户 ID 获取整个 JSON 对象和 JSON 对象?

【问题讨论】:

  • 您熟悉JsonConvert.SerializeObject() 方法吗?网上有很多关于如何做到这一点的例子……你试过谷歌搜索初学者吗?
  • @MethodMan 为什么要在 ApiController 中自己进行 JSON 转换?框架会为您处理。
  • 检查此stackoverflow.com/a/53813280/6522459,而不是返回日期时间返回您的列表
  • “我如何通过用户 ID 获取整个 JSON 对象和 JSON 对象?”...您需要两个操作方法。一个返回整个用户列表,另一个接受用户 ID 作为输入,选择整个用户并将其作为单个对象返回。要将对象/列表作为 JSON 返回,您无需在 Web API 中执行任何特殊操作,只需返回对象,.NET 将负责转换。
  • 先研究这个:docs.microsoft.com/en-us/aspnet/web-api/overview/…。它应该为您提供回答问题所需的模式。第一个代码示例中的“GetAllProducts()”和“GetProduct(int id)”方法类似于您所描述的(获取所有用户并获取单个用户)

标签: c# json api asp.net-web-api


【解决方案1】:

这是一个如何从 webapi 控制器返回 json 响应的示例

public class UserController : ApiController
{
    /// <summary>
    /// Get all Persons
    /// </summary>
    /// <returns></returns>     
    [HttpGet]
    // GET: api/User/GetAll
    [Route("api/User/GetAll")]
    public IHttpActionResult GetData()
    {
        return Ok(PersonDataAccess.Data);
    }

    /// <summary>
    /// Get Person By ID
    /// </summary>
    /// <param name="id">Person id </param>
    /// <returns></returns>
    // GET: api/User/GetByID/5
    [Route("api/User/GetByID/{id}")]
    public IHttpActionResult GetById(int id)
    {
        PersonDataAccess person = PersonDataAccess.Data.FirstOrDefault(p => p.Id = id);
        if (person != null)
        {
            return Ok(person);
        }
        else
        {
            return NotFound();
        }
    }
}

Check this from more information about response types

【讨论】:

  • 好的,这样更好。但是“用户 ID 的 JSON 对象”呢?问题的一部分?
  • 您仍应在答案中添加文字说明,而不仅仅是原始代码转储。
  • @YashKaranke 您应该在发布之前添加说明。不是之后。
  • @YashKaranke 您的静态数据没有地址。你打算使用 ef 或类似的东西从数据库中获取数据吗?
  • 如果你使用的是json文件,你可以像附加链接newtonsoft.com/json/help/html/DeserializeObject.htm
【解决方案2】:

在您的数据访问类中

class PersonDataAccess
{
    ...

    public IList<Person> GetData (int id) => Data.FirstOrDefault(x => x.Id == id);

}

在你的控制器内部

[HttpGet]
public IHttpActionResult GetData(int id)
{
    var result = (new PersonDataAccess ()).GetData(id);

    if (result == null)
        return NotFound();

    return Ok(result);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-08
    • 1970-01-01
    • 2017-07-22
    • 2014-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-12
    相关资源
    最近更新 更多