Susha Naidu
Susha Naidu

Reputation: 307

Returning file data in JSON format

I have a txt file which has some data in it. I would like to return the data in JSON format.

Why is it that when i do this in my controller, i am able to display the result (but not in JSON format):

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

However when i do this i get the result as: {"Data":{}}

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

If i just return result:

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

I do get the data however it is not in the Json format that i want e.g. {"Data": "Allthecontentinhere"}. I tried return Json(result) that did not work too.

Here is my FileReaderClient.cs class

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);
    }
}

How can i edit my code such that the data in the file is returned in JSON format?

Upvotes: 2

Views: 628

Answers (1)

NBaua
NBaua

Reputation: 684

You can use 'JsonConvert' / NewtonSoft's JSON.Net Library,

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

Hope this helps. --- N Baua

Upvotes: 1

Related Questions