【问题标题】:How can I return a list of data from my json file to my controller file in ASP.NET?如何将 json 文件中的数据列表返回到 ASP.NET 中的控制器文件?
【发布时间】:2021-08-05 22:44:23
【问题描述】:

我有一个包含艺术家姓名列表的 json 文件,我需要在我的控制器中返回这些姓名列表。如何访问控制器中的这些名称列表?我对使用 asp.net mvc 非常陌生。这是我尝试过的,但我不确定我是否走错了方向。

[HttpGet("/artist")]
public JsonResult ArtistNames()
{
    List<Artist> showNames = _____
        .Where(name => name.ArtistName)
        .ToList();
        
    return Json();
}

我把空白留在那里,因为我不确定我会在那里放什么,或者即使那是正确的方向。有人可以帮帮我吗?

这是我的艺术家模型:

public class Artist
{
    public string ArtistName;
    public string RealName;
    public int Age;
    public string Hometown;
    public int GroupId;
    public Group Group;
}

这不是一个真正的应用程序或任何东西,它只是一个练习作业。这是Json

[
  {"ArtistName":"RZA","RealName":"Robert Diggs","Age":47,"Hometown":"New York City","GroupId":1}, 
  {"ArtistName":"Lloyd Banks","RealName":"Christopher Lloyd","Age":34,"Hometown":"New York City","GroupId":2}, 
  {"ArtistName":"The Game","RealName":"Jayceon Taylor","Age":37,"Hometown":"Compton","GroupId":2},
  {"ArtistName":"Phife Dawg","RealName":"Malik Taylor","Age":45,"Hometown":"New York City","GroupId":3}, 
  {"ArtistName":"Busta Rhymes","RealName":"Trevor Smith","Age":44,"Hometown":"New York City","GroupId":0}, 
  {"ArtistName":"Dr Dre","RealName":"Andre Young","Age":51,"Hometown":"Compton","GroupId":4}
]

【问题讨论】:

  • 您是否首先将该 JSON 文件读入内存?
  • 你真的有一个实际的 json 文件放在某个地方并且你想发送它吗?通常,大多数应用程序从数据库中读取数据。
  • 您想阅读的艺术家信息在哪里?
  • 我添加了我拥有的 json 文件。这只是我正在做的一个作业(我是一名学生)。

标签: c# asp.net asp.net-mvc asp.net-core


【解决方案1】:

您可以使用此代码:

[HttpGet("/artist")]
public JsonResult ArtistNames(string artistName)
{
    var result = new List<Artist>();
    using (StreamReader r = new StreamReader("json file path!"))
    {
        string json = r.ReadToEnd();
        result = JsonConvert.DeserializeObject<List<Artist>>(json);
    }

    result = result
        .Where(name => name.ArtistName)
        .ToList();
        
    return result;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-21
    • 2019-04-11
    • 1970-01-01
    • 2017-07-27
    相关资源
    最近更新 更多