Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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?

alt

share|improve this question
    
stackoverflow.com/questions/9847564/… help you! – ssilas777 Mar 31 '13 at 3:55
    
@ssilas777 I don't think that's the same question. That's about returning XML vs. JSON as opposed to returning incorrect JSON. – Eilon Mar 31 '13 at 3:58
up vote 14 down vote accepted

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:

  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)
share|improve this answer

I found another solution which works also if anyone was interested.

public HttpResponseMessage Get()
{
    var stream = new FileStream(@"c:\data.json", FileMode.Open);

    var result = Request.CreateResponse(HttpStatusCode.OK);
    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

    return result;
}
share|improve this answer
2  
The generic HttpResponseMessage is now deprecated as it wasn't Type <T> safe.. stackoverflow.com/questions/10655350/… – Markive May 8 '13 at 1:36
4  
+1: The HttpResponseMessage may be deprecated, but it worked in the situation where the JSON property names were not valid CLR (e.g. had spaces in them). Your answer gave me the clue I needed to return generated raw text as JSON. Thanks – Gone Coding Jul 1 '13 at 7:34

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.