【发布时间】: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