2

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?

6
  • Since you are using WebAPI controllers (vs. ASP.Net MVC controllers that support Json() method) returning reasonable object should automatically produce JSON response. In current state of the post there is no way to know what you want to achieve and why your custom FileReaderClient does not represent data you want. Consider reading minimal reproducible example guidance on posting code and edit post to clarify. Commented Dec 21, 2017 at 3:23
  • Hi i have included my FileReaderClient class Commented Dec 21, 2017 at 3:29
  • Why not using the Server.Mappath-- using paths like "C:\\Users\\attsuap1\\Desktop\\1milliontest.txt" is not a good practice, Okey that may not be the actual reason of you not getting JSON, but still it shows you're not putting 100% in your code. Commented Dec 21, 2017 at 4:51
  • I used that at first and got an error Physical Path given but virtual path expected. Then i read that Server.Mappath is not needed when i know the path in one of the stackoverflow answers Commented Dec 21, 2017 at 4:59
  • If I use your code with return result, I get a valid JSON. What do you get? You said: "I do get the data however it is not in Json format". Commented Dec 21, 2017 at 10:36

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Hi thanks for helping me. So should i replace the codes in my FileReaderClient.cs to this?
And will these codes display the data that is in my 1milliontest.txt file?
Ideally it should, however that something, you need to try. Yes , you can check

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.