Return string containing valid Json with Nancy

I get a string containing valid JSON from another service. I would just like to forward this line with Nancy, but also set the content type to "application / json", which will allow me to remove the need to use $ .parseJSON (data) on the client side.

If I use Response.AsJson, it seems to distort the JSON in the string and add escape characters. I could create a Stream with a string and set the response type to something like this:

Response test = new Response(); test.ContentType = "application/json"; test.Contents = new MemoryStream(Encoding.UTF8.GetBytes(myJsonString)); 

but would like to know if there is an easier way?

+42
json nancy
Sep 29 '11 at 12:03
source share
4 answers

I like that you think there should be a better way, because you need to use 3 lines of code, I think something is saying about Nancy :-)

I can't think of a โ€œbetterโ€ way to do this, you can either do it with the GetBytes method:

 Get["/"] = _ => { var jsonBytes = Encoding.UTF8.GetBytes(myJsonString); return new Response { ContentType = "application/json", Contents = s => s.Write(jsonBytes, 0, jsonBytes.Length) }; }; 

Or the way to "distinguish a string":

 Get["/"] = _ => { var response = (Response)myJsonString; response.ContentType = "application/json"; return response; }; 

Both do the same thing - the last less code, the first more descriptive (imo).

+48
Sep 30 '11 at 12:05
source share

Nancy seems to have a great Response.AsJson extension method:

 Get["/providers"] = _ => { var providers = this.interactiveDiagnostics .AvailableDiagnostics .Select(p => new { p.Name, p.Description, Type = p.GetType().Name, p.GetType().Namespace, Assembly = p.GetType().Assembly.GetName().Name }) .ToArray(); return Response.AsJson(providers); }; 
+63
Nov 04 '12 at 15:56
source share

This also works:

 Response.AsText(myJsonString, "application/json"); 
+10
Jul 28 '16 at 15:45
source share

To a large extent, how you do it. You could do

 var response = (Response)myJsonString; response.ContentType = "application/json"; 

You can simply create an extension method in IResponseFormatter and provide your own AsXXXX helper. With release 0.8, some answer extensions will appear, so you can do things like WithHeader (..), WithStatusCode (), etc. -

+5
Sep 30 '11 at 11:56
source share



All Articles