Indented output for JSON Service Responses

Is there a jsconfig option to indent JSON output for service responses? I know there are the .Dump options in ServiceStack.Text, but is there any way to have that as a client option for a serialized service response?

There isn’t, if you’re viewing JSON responses in Chrome install the JSON Formatter Chrome extension which automatically provides syntax highlighting and collapsible regions to JSON responses.

The Dump() Utils displays a JSV indented friendly output, to indent JSON you’d instead use IndentJson(), e.g:

var prettyJson = dto.ToJson().IndentJson();

Which is how you could return an indented JSON string in your Service, but that’d be unnecessarily inefficient. It’s better to view the indented JSON in your client when needed, you can even paste the JSON directly in the JS Console of Chrome’s Web Inspector which returns a navigable JS object literal.

1 Like

I’ve found the Chrome extension helpful.
I still feel like there should be a built-in option to enable indentation. Stripe’s API, by default, provides indented responses, so performance issues can’t be that bad if they are doing that globally on their scale.

It’s likely not expensive relative to your Services implementation, but it’s additional processing that’s unnecessary, which your service can do by returning an indented JSON string:

return dto.ToJson().IndentJson();

There’s no configuration option in the JSON Serializer, it’s only available as a post output transformation.

Is there a way to accomplish this without changing the return signature of every service endpoint? I don’t want to break other potential output types (HTML5, CSV).

I agree this shouldn’t be the default, the original ask was for an option the client could opt-in to.

You could override the built-in JSON Serialization with a customized impl, e.g:

    (r, o, s) => {
        var json = JsonDataContractSerializer.Instance.SerializeToString(o);
        MemoryProvider.Instance.Write(s, json.IndentJson().AsMemory());
    }, JsonDataContractSerializer.Instance.DeserializeFromStream);

But as I said it’s unnecessarily inefficient, also it makes use of a new MemoryProvider API in v5.6.1 for reducing allocations in ASP .NET Core, with prior versions you can write serialized UTF-8 bytes, i.e:

var utf8 = json.IndentJson().ToUtf8Bytes();
s.Write(utf8, 0, utf8.Length);