ojhawkins ojhawkins - 2 years ago 496
Javascript Question

Return Json file with ASP.NET Web API

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?


Answer Source

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(

    object jsonObject = JsonConvert.DeserializeObject(allText);
    return jsonObject;

This will:

  1. Read the file as a string
  2. Parse it as a JSON object into a CLR object
  3. Return it to Web API so that it can be formatted as JSON (or XML, or whatever)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download