【问题标题】:Returning file data in JSON format以 JSON 格式返回文件数据
【发布时间】:2018-02-09 11:33:01
【问题描述】:

我有一个 txt 文件,里面有一些数据。我想以 JSON 格式返回数据。

为什么当我在控制器中执行此操作时,我能够显示结果(但不是 JSON 格式):

public IHttpActionResult Get()
{
    return new FileReaderClient("C:\\Users\\attsuap1\\Desktop\\1milliontest.txt");
}

但是,当我这样做时,我得到的结果是:{"Data":{}}

public IHttpActionResult Get()
    {
        var result = new FileReaderClient("C:\\Users\\attsuap1\\Desktop\\1milliontest.txt");
        return Ok(new { Data = result });
    }

如果我只是return result:

 public IHttpActionResult Get()
    {
        var result = (new FileReaderClient("C:\\Users\\attsuap1\\Desktop\\1milliontest.txt"));
        return result;
    }

我确实得到了数据,但是它不是我想要的 Json 格式,例如{"Data": "Allthecontentinhere"}。我试过return Json(result) 也没有用。

这是我的 FileReaderClient.cs 类

public class FileReaderClient : IHttpActionResult
{
    private readonly string filePath;
    private readonly string contentType;

    public FileReaderClient(string filePath, string contentType = null)
    {
        this.filePath = filePath;
        this.contentType = contentType;
    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        return Task.Run(() =>
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StreamContent(File.OpenRead(filePath))
            };

            var contentType = this.contentType ?? MimeMapping.GetMimeMapping(Path.GetExtension(filePath));
            response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);

            return response;
        }, cancellationToken);
    }
}

如何编辑我的代码以使文件中的数据以 JSON 格式返回?

【问题讨论】:

  • 由于您使用 WebAPI 控制器(与支持 Json() 方法的 ASP.Net MVC 控制器相比)返回合理的对象应自动生成 JSON 响应。在帖子的当前状态下,无法知道您想要实现什么以及为什么您的自定义 FileReaderClient 不代表您想要的数据。考虑阅读minimal reproducible example 发布代码指南和edit 帖子以澄清。
  • 嗨,我已经包含了我的 FileReaderClient 类
  • 为什么不使用 Server.Mappath——使用像“C:\\Users\\attsuap1\\Desktop\\1milliontest.txt”这样的路径不是一个好习惯,Okey 可能不是你没有得到 JSON 的实际原因,但它仍然表明你没有把 100% 放在你的代码中。
  • 我一开始使用它并得到一个错误Physical Path given but virtual path expected。然后我读到当我知道stackoverflow答案之一中的路径时不需要Server.Mappath
  • 如果我将您的代码与return result 一起使用,我会得到一个有效的 JSON。你得到了什么?你说:“我确实得到了数据,但它不是 Json 格式”.

标签: c# asp.net json


【解决方案1】:

您可以使用'JsonConvert' / NewtonSoft 的 JSON.Net 库,

var million_records;
using(StreamReader sr = new StreamReader(Server.MapPath("~/Uploads/1milliontest.json")))
{
      million_records= JsonConvert.DeserializeObject<List<MillionData>>(sr.ReadToEnd());
}
return million_records;

希望这会有所帮助。 --- N Baua

【讨论】:

  • 您好,感谢您帮助我。那么我应该将 FileReaderClient.cs 中的代码替换为这个吗?
  • 这些代码会显示我1milliontest.txt文件中的数据吗?
  • 理想情况下应该是这样,但是,您需要尝试一下。是的,你可以检查
猜你喜欢
  • 2011-06-11
  • 2017-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-11
  • 1970-01-01
  • 2017-08-08
  • 2014-09-04
相关资源
最近更新 更多