On Wed, 08 May 2013 12:23:19 GMT, Michal Minich wrote:

Hi, I just started to use vibe.d

I want to generate some JSON for ajax calls. And first thing I tried was .dt templates. They would be quite good match for it, but I don't know how to set content type to "application/json" for them.

Second approach I took was to try to direct write to response stream. But only method that allows setting content type is writeBody. So I'm forced to generate full JSON string before, and then write it.

I would prefer to use .dt and also being able to directly set content type (by property) and be able to write to OutputStream bodyWriter...

Thank you.

Hi. The Diet templates are really very specific to HTML (or to a lesser extent also XML), so those are not really an option. However, there are two possibilities to output a JSON string without writing it to memory first:

  1. HttpServerResponse.writeJsonBody - you, like me, have probably overlooked this in the documentation because it is erreneously documented as a template
  2. Set the content type manually to "application/json; charset=UTF-8" and then use bodyWriter to write the response

Both methods require to build the full in-memory representation of the JSON object first, though (can be type Json or any type that can be serialized to Json). Another alternative, which I haven't yet gotten around to try, is to use embd or mustache-d, two general purpose alternatives to the Diet template format.

I'll look into why the documentation is broken now...