Edit on GitHub

Customize JSON Responses

The JSON Responses for all ServiceStack Services can be configured Globally, individually per-Service or customized per-request by the client using the ?jsconfig QueryString modifier.

Global Default JSON Configuration

ServiceStack uses the ServiceStack.Text Serializers for its built-in JSON/JSV and CSV serialization. The serialization can be customized globally by configuring the JsConfig or type-specific JsConfig<T> static classes with your preferred defaults, e.g:

public override void Configure(Container container)
{
    JsConfig.EmitLowercaseUnderscoreNames = true; 
    JsConfig.ExcludeDefaultValues = true;

    JsConfig<Guid>.SerializeFn = guid => guid.ToString("D");
    JsConfig<TimeSpan>.SerializeFn = time => 
        (time.Ticks < 0 ? "-" : "") + time.ToString("hh':'mm':'ss'.'fffffff");
}

Customize JSON Responses in Service

The Global Defaults can be overridden on a adhoc basis by returning your Response DTO in a custom HttpResult configured with a custom JS Config Scope, e.g:

return new HttpResult(responseDto) {
    ResultScope = () => JsConfig.With(
        emitLowercaseUnderscoreNames:true, excludeDefaultValues:true)
};

This has the same behavior for your Service Responses as creating a Custom Config Scope for adhoc Serialization that overrides Global Configuration, e.g:

using (JsConfig.With(emitLowercaseUnderscoreNames:true, excludeDefaultValues:true))
{
    var json = dto.ToJson();
}

Customize JSON Responses from Client

The JSON and JSV Responses for all Services (inc. Auto Query Services) can also be further customized with the new ?jsconfig QueryString param which lets your Service consumers customize the returned JSON Response to their preference. This works similar to having wrapped your Service response in a HttpResult with a Custom ResultScope in the Service implementation to enable non-default customization of a Services response, e.g:

/service?jsconfig=EmitLowercaseUnderscoreNames,ExcludeDefaultValues

Works similarly to:

return new HttpResult(new { TheKey = "value", Foo=0 }) {
    ResultScope = () => JsConfig.With(
        emitLowercaseUnderscoreNames:true, excludeDefaultValues:true)
};

Which results in lowercase_underscore key names with any properties with default values removed:

{"the_key":"value"}

It also supports cascading server and client ResultScopes, with the client ?jsconfig taking precedence.

Nearly all JsConfig scope options are supported other than delegates and complex type configuration properties.

Camel Humps Notation

JsConfig also supports Camel Humps notation letting you target a configuration by just using the Uppercase Letters in the property name which is also case-insensitive so an equivalent shorter version of the above config can be:

?jsconfig=ELUN,edv

Camel Humps also works with Enum Values so both these two configurations are the same:

?jsconfig=DateHandler:UnixTime
?jsconfig=dh:ut

Custom JSON Live Example

AutoQuery Viewer makes use of this feature in order to return human readable dates using the new ISO8601DateOnly DateHandler Enum Value as well as appending ExcludeDefaultValues when specifying custom fields so that any unpopulated value type properties with default values are excluded from the JSON Response. Here’s a live example of this comparing the default Response with the customized JSON Response:

Custom JSON Settings

The presence of a bool configuration property will be set to true unless they have a false or 0 value in which case they will be set to false, e.g:

?jsconfig=ExcludeDefaultValues:false

For a quick reference the following bool customizations are supported:

NameAlias
EmitCamelCaseNameseccn
EmitLowercaseUnderscoreNameselun
IncludeNullValuesinv
IncludeNullValuesInDictionariesinvid
IncludeDefaultEnumside
IncludePublicFieldsipf
IncludeTypeInfoiti
ExcludeTypeInfoeti
ConvertObjectTypesIntoStringDictionarycotisd
TreatEnumAsIntegerteai
TryToParsePrimitiveTypeValuesttpptv
TryToParseNumericTypettpnt
ThrowOnDeserializationErrortode
EscapeUnicodeeu
EscapeHtmlCharsehc
PreferInterfacespi
SkipDateTimeConversionsdtc
AlwaysUseUtcauu
AssumeUtcau
AppendUtcOffsetauo
EscapeHtmlCharsehc
EscapeUnicodeeu

DateHandler (dh)

TimestampOffsetto
DCJSCompatibledcjsc
ISO8601iso8601
ISO8601DateOnlyiso8601do
ISO8601DateTimeiso8601dt
RFC1123rfc1123
UnixTimeut
UnixTimeMsutm

TimeSpanHandler (tsh)

DurationFormatdf
StandardFormatsf

PropertyConvention (pc)

Stricts
Lenientl

Create Custom Scopes using String config

You can also create a scope from a string manually using JsConfig.CreateScope(), e.g:

using (JsConfig.CreateScope("EmitLowercaseUnderscoreNames,ExcludeDefaultValues,dh:ut")) 
{
    var json = dto.ToJson();
}

If you don’t wish for consumers to be able to customize JSON responses this feature can be disabled with Config.AllowJsConfig=false.