|
| 1 | +--- |
| 2 | +description: Describes how the JSON serialization within Umbraco can be customized. |
| 3 | +--- |
| 4 | + |
| 5 | +# JSON Serialization |
| 6 | + |
| 7 | +Umbraco uses JSON as a format to serialize information to the database and for output. For example, the configuration of data types and the property values of complex editors are serialized to JSON for persistence. |
| 8 | + |
| 9 | +The serializers within Umbraco uses a `JavascriptEncoder` which only considers basic latin characters as unnecessary to encode. |
| 10 | + |
| 11 | +## Implementing Custom Behavior |
| 12 | + |
| 13 | +For projects making use of non-Latin characters you may want to amend this behavior. By doing so you can reduce the space the serialized information takes up in the database. |
| 14 | + |
| 15 | +We support this by abstracting the default behavior behind the `IJsonSerializerEncoderFactory` interface found in the `Umbraco.Cms.Core.Serialization` namespace. |
| 16 | + |
| 17 | +You can implement your own version of this interface and register it via a composer. This is shown in the following example that marks Cyrillic characters as excluded for encoding: |
| 18 | + |
| 19 | +```csharp |
| 20 | +using System.Text.Encodings.Web; |
| 21 | +using System.Text.Unicode; |
| 22 | +using Umbraco.Cms.Core.Composing; |
| 23 | +using Umbraco.Cms.Core.Serialization; |
| 24 | +using Umbraco.Cms.Infrastructure.Serialization; |
| 25 | + |
| 26 | +namespace Umbraco.Cms.Web.UI.Custom.SystemTextConfigurationEditor; |
| 27 | + |
| 28 | +public class SystemTextConfigurationEditorComposer : IComposer |
| 29 | +{ |
| 30 | + public void Compose(IUmbracoBuilder builder) |
| 31 | + { |
| 32 | + builder.Services.AddUnique<IJsonSerializerEncoderFactory, MyConfigurationEditorJsonSerializerEncoderFactory>(); |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +internal class MyConfigurationEditorJsonSerializerEncoderFactory : IJsonSerializerEncoderFactory |
| 37 | +{ |
| 38 | + public JavaScriptEncoder CreateEncoder<TSerializer>() |
| 39 | + where TSerializer : IJsonSerializer |
| 40 | + { |
| 41 | + return JavaScriptEncoder.Create(UnicodeRanges.BasicLatin, UnicodeRanges.Cyrillic); |
| 42 | + } |
| 43 | +} |
| 44 | +``` |
| 45 | + |
| 46 | +For reference, the default implementation can be found [in the Umbraco CMS source code](https://github.com/umbraco/Umbraco-CMS/blob/main/src/Umbraco.Infrastructure/Serialization/DefaultJsonSerializerEncoderFactory.cs). |
| 47 | + |
| 48 | + |
0 commit comments