Go to content

Bulletcode.NET

JSON Serialization

REST API

Bulletcode.NET makes it easy to implement a REST API and to consume it in client applications. It ensures that both the API servers and the client applications use the same serialization options. They are based on the built-in Web scenario used by JsonSerializer, where the camelCase name formatting is used and property names are case-insensitive, with the following additional settings:

  • null values are ignored during serialization (DefaultIgnoreCondition is set to WhenWritingNull)
  • read-only properties are not serialized (IgnoreReadOnlyProperties is set to true)

Bulletcode.NET also ensures that errors are properly handled and serialized by the REST API. Errors occurring in the API are serialized as the ErrorResult object, which contains the reason of the error, message and optional details. The ErrorReason constants provide a standardized way to distinguish between validation errors, authentication and authorization errors and unexpected errors. The IApiClient service throws an ErrorResultException containing this information when an API error is encountered and successfully deserialized. See the Diagnostics and API Client chapters for more information.

The JsonBindNever attribute can be used to indicate that a model property should be ignored when deserializing request data sent from the API client to the server. It is, however, deserialized when returning data from the server to the client. It’s similar to the BindNever attribute, which is used when data is sent using HTML forms, but it works for JSON requests.

Inline JavaScript code

The JsSerializer helper class can be used for creating inline JavaScript code which can be safely injected into HTML pages. In addition to serializing values using JSON format, it supports the following features:

  • Embedding JavaScript expressions in serialized data. Those expressions should be wrapped in the JsExpression objects. This feature is used to serialize translations, which include plural rules converted to JavaScript functions for better performance.

WARNING

Expressions wrapped in JsExpression should never contain any user-provided values to avoid XSS attacks. Use them with caution.

  • Serializing data which may include values serialized with different serialization options, or values whose serialized representation is cached and reused. This can be done using the SerializeToRawJsonValue() method. This feature is used by the ClientView serialization mechanism.

NOTE

The SerializeToRawJsonValue() method internally stores data as byte[], so it’s much faster and uses less memory than the SerializeToNode() method, which first serializes data to a memory stream and then parses it in order to create a DOM representation.

JsSerializer also contains a Format() method which serializes all its arguments before passing them to String.Format().