gpt4 book ai didi

javascript - 使用 WebAPI Controller 序列化复杂的 json 对象

转载 作者:行者123 更新时间:2023-11-29 23:56:53 24 4
gpt4 key购买 nike

我是 angularjs 和 ASP.NET webapi 的新手。我正在处理一些要求,我的基表如下所示

CurriculumID    SubjectArea CourseNumber
------------ ----------- ------------
303 GHIJ 101
304 ABCD 102
305 MNPQ 103
306 WXYZ 104

lookupId lookupValue
-------- -----------
1 Very Useful
2 Somewhat Useful
3 Not Useful
4 Not Applicable
5 Elsewhere

我为这些表创建了两个模型类(类(class)和查找)。我如何使用 webapi Controller 方法 public HttpResponseMessage getData(...)

生成如下所示的 JSon 数据

我需要如下所示的结果 JSON 数据

    $scope.questions = [
{
"CurriculumID": "303", "SubjectArea": "GHIJ", "CourseNumber": "101", "answers": [
{ "lookupValue": "Very Useful","lookupId":"1" },
{ "lookupValue": "Somewhat Useful", "lookupId": "2" },
{ "lookupValue": "Not Useful", "lookupId": "3" },
{ "lookupValue": "Not Applicable", "lookupId": "4" },
{ "lookupValue": "Elsewhere", "lookupId": "5" }
]
},
{
"CurriculumID": "304", "SubjectArea": "ABCD", "CourseNumber": "102", "answers": [
{ "lookupValue": "Very Useful","lookupId":"1" },
{ "lookupValue": "Somewhat Useful", "lookupId": "2" },
{ "lookupValue": "Not Useful", "lookupId": "3" },
{ "lookupValue": "Not Applicable", "lookupId": "4" },
{ "lookupValue": "Elsewhere", "lookupId": "5" }
]
}
.
.
.
];

请查看此链接以获得更好的理解 https://plnkr.co/edit/73oA3rsrre8gqYX9V25W?p=preview

那么getData(生成JSon数据)这两个方法怎么写呢。谁能帮我在 ASP.NET 中序列化这个结构

https://plnkr.co/edit/73oA3rsrre8gqYX9V25W?p=preview

最佳答案

假设您已使用以下实体为 SQL 表建模:

public class Question
{
[Key]
public int CurriculumID { get; set; }

public string SubjectArea { get; set; }

public int CourseNumber { get; set; }
}

public class Rating
{
[Key]
public int LookupId { get; set; }

public string LookupValue { get; set; }
}

下一步是定义一个 View 模型来表示您要序列化的结构:

public class QuestionViewModel
{
public int CurriculumID { get; set; }

public string SubjectArea { get; set; }

public int CourseNumber { get; set; }

public IList<RatingViewModel> Answers { get; set; }
}

public class RatingViewModel
{
public int LookupId { get; set; }

public string LookupValue { get; set; }
}

然后在您的 Controller 中,您可以从数据库中获取实体并从中填充 View 模型:

public class QuestionsController: ApiController
{
[HttpGet]
[Route("api/questions")]
public IHttpActionResult Get()
{
using (var db = new MyDbContext())
{
IList<Rating> ratings = db.Ratings.ToList();
IList<Question> questions = db.Questions.ToList();
IList<QuestionViewModel> result = questions.Select(q => new QuestionViewModel
{
CurriculumID = q.CurriculumID,
SubjectArea = q.SubjectArea,
CourseNumber = q.CourseNumber,
Answers = ratings.Select(r => new RatingViewModel
{
LookupId = r.LookupId,
LookupValue = r.LookupValue,
}).ToList(),
}).ToList();

return this.Ok(result);
}
}
}

关于javascript - 使用 WebAPI Controller 序列化复杂的 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41370691/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com