I am trying to return a JSON file using ASP.NET Web API (for testing).
public string[] Get() { string[] text = System.IO.File.ReadAllLines(@"c:\data.json"); return text; }
In Fiddler this does appear as a Json type but when I debug in Chrome and view the object it appears as and array of individual lines (left). The right image is what the object should look like when I am using it.
Can anyone tell me what I should return to achieve a Json result in the correct format?
ContentType = "application/json; charset=utf-8"; Response. Write(json); Response. End(); To convert a C# object to JSON you can use a library such as Json.NET.
Learn the three ways you can return data from your ASP.NET Core Web API action methods. We have three ways to return data and HTTP status codes from an action method in ASP.NET Core. You can return a specific type, return an instance of type IActionResult, or return an instance of type ActionResult.
Does the file already has valid JSON in it? If so, instead of calling File.ReadAllLines
you should call File.ReadAllText
and get it as a single string. Then you need to parse it as JSON so that Web API can re-serialize it.
public object Get() { string allText = System.IO.File.ReadAllText(@"c:\data.json"); object jsonObject = JsonConvert.DeserializeObject(allText); return jsonObject; }
This will:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With