gpt4 book ai didi

c# - 以 JSON 格式返回文件数据

转载 作者:太空宇宙 更新时间:2023-11-03 12:19:51 27 4
gpt4 key购买 nike

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

为什么当我在我的 Controller 中执行此操作时,我能够显示结果(但不是 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 });
}

如果我只是返回结果:

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

我确实得到了数据,但是它不是我想要的 Json 格式,例如{“数据”:“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 格式返回?

最佳答案

您可以使用 '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 鲍阿

关于c# - 以 JSON 格式返回文件数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47917134/

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