-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Customize JSON Responses
This page has moved to docs.servicestack.net/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.
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");
}
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)
};
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.
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
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:
- http://github.servicestack.net/repos.json?fields=Name,Homepage,Language,Updated_At
- http://github.servicestack.net/repos.json?fields=Name,Homepage,Language,Updated_At&jsconfig=edv,dh:iso8601do
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:
Name | Alias |
---|---|
EmitCamelCaseNames | eccn |
EmitLowercaseUnderscoreNames | elun |
IncludeNullValues | inv |
IncludeNullValuesInDictionaries | invid |
IncludeDefaultEnums | ide |
IncludePublicFields | ipf |
IncludeTypeInfo | iti |
ExcludeTypeInfo | eti |
ConvertObjectTypesIntoStringDictionary | cotisd |
TreatEnumAsInteger | teai |
TryToParsePrimitiveTypeValues | ttpptv |
TryToParseNumericType | ttpnt |
ThrowOnDeserializationError | tode |
EscapeUnicode | eu |
PreferInterfaces | pi |
SkipDateTimeConversion | sdtc |
AlwaysUseUtc | auu |
AssumeUtc | au |
AppendUtcOffset | auo |
DateHandler (dh) | |
TimestampOffset | to |
DCJSCompatible | dcjsc |
ISO8601 | iso8601 |
ISO8601DateOnly | iso8601do |
ISO8601DateTime | iso8601dt |
RFC1123 | rfc1123 |
UnixTime | ut |
UnixTimeMs | utm |
TimeSpanHandler (tsh) | |
DurationFormat | df |
StandardFormat | sf |
PropertyConvention (pc) | |
Strict | s |
Lenient | l |
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
.
- Why ServiceStack?
- Important role of DTOs
- What is a message based web service?
- Advantages of message based web services
- Why remote services should use separate DTOs
-
Getting Started
-
Designing APIs
-
Reference
-
Clients
-
Formats
-
View Engines 4. Razor & Markdown Razor
-
Hosts
-
Security
-
Advanced
- Configuration options
- Access HTTP specific features in services
- Logging
- Serialization/deserialization
- Request/response filters
- Filter attributes
- Concurrency Model
- Built-in profiling
- Form Hijacking Prevention
- Auto-Mapping
- HTTP Utils
- Dump Utils
- Virtual File System
- Config API
- Physical Project Structure
- Modularizing Services
- MVC Integration
- ServiceStack Integration
- Embedded Native Desktop Apps
- Auto Batched Requests
- Versioning
- Multitenancy
-
Caching
-
HTTP Caching 1. CacheResponse Attribute 2. Cache Aware Clients
-
Auto Query
-
AutoQuery Data 1. AutoQuery Memory 2. AutoQuery Service 3. AutoQuery DynamoDB
-
Server Events
-
Service Gateway
-
Encrypted Messaging
-
Plugins
-
Tests
-
ServiceStackVS
-
Other Languages
-
Amazon Web Services
-
Deployment
-
Install 3rd Party Products
-
Use Cases
-
Performance
-
Other Products
-
Future