【问题标题】:Read records from JSON file in ASP.net Core (v2.1) WebAPI从 ASP.net Core (v2.1) WebAPI 中的 JSON 文件读取记录
【发布时间】:2021-08-11 10:09:50
【问题描述】:

我是 asp.net core WebApi 的新手,我正在尝试从一个有效的 json 文件中读取数据,该文件保存在我的 webapi 中名为 mydata 的文件夹中

/mydata/userData.json

userData.json:

{
    "users": [
        {
            "id": 1,
            "firstName": "John",
            "lastName": "Doe"
        },
        {
            "id": 2,
            "firstName": "Jane",
            "lastName": "Doe"
        }
}

我编写了一个 Web 方法,它将输入作为名字,并返回单个用户对象(在多个结果中首先找到的记录)。

UserController.cs:

[Route("user/{firstName}")]  
public User GetUser(string firstName)  
{  
using (StreamReader r = new StreamReader("~/mydata/userData.json"))
    {
         string json = r.ReadToEnd();
         User item =JsonConvert.DeserializeObject<User>(json);
    }
    var user = User; 
    return user;  
} 

我面临以下问题:

  1. 我无法映射文件 userData.json,我尝试了 Server.MapPath 但它看起来不可用,httpcontext 也不起作用。
  2. 我不明白如何从这个 api 返回一个用户对象,它将在反应应用程序中使用。

【问题讨论】:

  • 您的文件名为user.json,但在您的StreamReader 中,您正尝试读取具有不同名称userData.json 的文件。是不是打错字了?
  • @Izzy 打错字了,我改正了。谢谢

标签: c# asp.net-core-webapi asp.net-core-2.0


【解决方案1】:

您可以通过使用IHostingEnvironment 获取根路径和Path.Combine() 方法来实现此目的。所以你的控制器应该是这样的:

public class UserController : Controller
{
    private readonly IHostingEnvironment _hostingEnvironment;

    public UserController(IHostingEnvironment hostingEnvironment)
    {
        _hostingEnvironment = hostingEnvironment;
    }

    [Route("user/{firstName}")]
    public User GetUser(string firstName)
    {
        var rootPath = _hostingEnvironment.ContentRootPath; //get the root path

        var fullPath = Path.Combine(rootPath, "mydata/user.json"); //combine the root path with that of our json file inside mydata directory

        var jsonData = System.IO.File.ReadAllText(fullPath); //read all the content inside the file

        if (string.IsNullOrWhiteSpace(jsonData)) return null; //if no data is present then return null or error if you wish

        var users = JsonConvert.DeserializeObject<List<User>>(jsonData); //deserialize object as a list of users in accordance with your json file

        if (users == null || users.Count == 0) return null; //if there's no data inside our list then return null or error if you wish

        var user = users.FirstOrDefault(x => x.FirstName == firstName); //filter the list to match with the first name that is being passed in

        return user;

    }
}

请注意: IHostingEnvironment 将在未来的版本中被删除,因此如果您可以升级您的框架,那么请这样做,这样您就可以使用推荐的 IWebHostEnvironment 类型。

【讨论】:

  • 谢谢,我正在尝试这种方法。并收到此错误: - $exception {"无法将当前 JSON 对象(例如 {\"name\":\"value\"})反序列化为类型 'System.Collections.Generic.List`1[App.Models.User ]' 因为该类型需要 JSON 数组(例如 [1,2,3])才能正确反序列化。\r\n要修复此错误,请将 JSON 更改为 JSON 数组(例如 [1,2,3])或 . .....我会继续调试的。
  • 这是因为 JSON 文件包含一个包含用户列表的“用户”对象(json 文件不直接包含列表)而导致的实现错误吗?
  • 您在问题中包含的 JSON 文件内容,语法不正确,因为您缺少结束 ]。在昨天发布我的答案之前,我添加了结尾 ] 并设法反序列化而没有任何问题。如果您JSON 文件内容已更改,请将其添加到您的问题中,我会更新我的答案。
【解决方案2】:

首先,在 asp.net core 中,您只能(默认情况下)从 wwwroot 文件夹中读取数据。如果你想改变它,那么refer here

其次,您试图仅读取单个对象,但在您的 json 文件中,有多个用户对象。你可以通过用这个List&lt;User&gt; items = JsonConvert.DeserializeObject&lt;List&lt;User&gt;&gt;(json);替换你的代码User item =JsonConvert.DeserializeObject&lt;User&gt;(json);来解决这个问题

最后,正如 cmets 中提到的,当你 StreamRead 时,你引用了错误的文件......另外,如果你 reference the file using enviromental variables 会更好

希望我能帮上忙!

【讨论】:

    【解决方案3】:

    1-) 示例路径;

    StreamReader r = new StreamReader(@"C:\Users\Suleyman\Desktop\users.json");
    

    2-) 样本;

      public List<User> GetUser(string firstName){}
    
    
    List<User> item = JsonConvert.DeserializeObject<List<User>>(json);
    

    【讨论】:

      【解决方案4】:

      这是一个工作演示:

      /mydata/userData.json:

      {
        "users": [
          {
            "id": 1,
            "firstName": "John",
            "lastName": "Doe"
          },
          {
            "id": 2,
            "firstName": "Jane",
            "lastName": "Doe"
          }
        ]
      }
      

      项目结构:

      型号:

      public class User
          {
              public List<UserModel> users { get; set; }
          }
          public class UserModel
          {
              public int id { get; set; }
              public string firstName { get; set; }
              public string lastName { get; set; }
      
      
          }
      

      行动:

      [Route("user/{firstName}")]
              public User GetUser(string firstName)
              {
                  using (StreamReader r = new StreamReader("mydata/userData.json"))
                  {
                      string json = r.ReadToEnd();
                      User item = JsonConvert.DeserializeObject<User>(json);
                      return item;
                  }
                  return new User();
                 
              }
      

      结果:

      【讨论】:

        猜你喜欢
        • 2017-09-07
        • 1970-01-01
        • 1970-01-01
        • 2015-10-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-29
        相关资源
        最近更新 更多