akash
akash

Reputation: 55

how to download json object in file asp.net

i have class

    class abc{
       [JsonPropertyName("firstName")]
       public string FirstName{get; set;}

       [JsonPropertyName("lastName")]
       public string LastName{get; set;} }

i am assigning some values in it one method.

     public void DownloadJson(){
     abc abcModel= new abc(){ FirstName="Tom", LastName="Torres"};

     var test = JsonConvert.SerializeObject(abcModel);
     }

i want to save(download) this test object in json file on my browserwithout directing in new window just simply download it in same method DownloadJson() and in current window.

Upvotes: 2

Views: 5863

Answers (2)

akash
akash

Reputation: 55

it worked.

   fileName="xyz.json"

   byte[] bytes = System.Text.Encoding.UTF8.GetBytes(test);

   var content = new System.IO.MemoryStream(bytes);
   return File(content , "application/json", fileName);

Upvotes: 2

M Leipper
M Leipper

Reputation: 397

public ContentResult DownloadJson(){
 var builder = new StringBuilder();
 abc abcModel= new abc(){ FirstName="Tom", LastName="Torres"};
 var test = JsonConvert.SerializeObject(abcModel);
 builder.Append($"{test}")
 var fileName = "someName.JSON";

        Response.Headers.Add("Content-Disposition", $"attachment; filename=\"{fileName}\"");

        return Content(data, "text/plain");

 }

have you tried returning a ContentResult?

Upvotes: 1

Related Questions