Typescript Deserialize Json To Class

-->

This article shows how to use the System.Text.Json namespace to serialize to and deserialize from JavaScript Object Notation (JSON). If you're porting existing code from Newtonsoft.Json, see How to migrate to System.Text.Json.

Code samples

Apr 26, 2019 I started working with TypeScript about two years ago. Most of the time I read a JSON object from a remote REST server. This JSON object has all the properties of a TypeScript class. There is a question always buzz my head: How do I cast/parse the received JSON object to an instance of a corresponding class? Feb 03, 2018 Cerialize. Easy serialization through ES7/Typescript annotations. This is a library to make serializing and deserializing complex JS objects a breeze. It works by applying meta data annotations (as described in ES7 proposal and experimental Typescript feature) to fields in a user defined class. TypeScript queries related to “json object from typescript class ” typescript json response; json object typescript example; json object to typecript interface; typescript how to convert json to models; read json and according to a field map to a data type typescript; convert a json file to a class object in typescript. You can use JSON deserialization extension - cz.habarta.typescript.generator.ext.JsonDeserializationExtension - which generates methods that allow to 'deserialize' JSON data into instances of generated classes.It adds 'copy' methods to classes which receive pure object, create new instance of the class and recursivelly copy properties from data object to the instance of class. A typescript library to deserialize json into typescript classes and serialize classes into json. Installation npm install typescript-json-serializer -save # or yarn add typescript-json-serializer You also need to set experimentalDecorators and emitDecoratorMetadata to true into the tsconfig.json file.

The code samples in this article:

  • Use the library directly, not through a framework such as ASP.NET Core.

  • Use the JsonSerializer class with custom types to serialize from and deserialize into.

    For information about how to read and write JSON data without using JsonSerializer, see How to use the JSON DOM, Utf8JsonReader, and Utf8JsonWriter.

  • Use the WriteIndented option to format the JSON for human readability when that is helpful.

    For production use, you would typically accept the default value of false for this setting, since adding unnecessary whitespace may incur a negative impact on performance and bandwidth usage.

  • Refer to the following class and variants of it:

Visual Basic support

Parts of System.Text.Json use ref structs, which are not supported by Visual Basic. If you try to use System.Text.Json ref struct APIs with Visual Basic you get BC40000 compiler errors. The error message indicates that the problem is an obsolete API, but the actual issue is lack of ref struct support in the compiler. The following parts of System.Text.Json aren't usable from Visual Basic:

  • The Utf8JsonReader class. Since the JsonConverter<T>.Read method takes a Utf8JsonReader parameter, this limitation means you can't use Visual Basic to write custom converters. A workaround for this is to implement custom converters in a C# library assembly, and reference that assembly from your VB project. This assumes that all you do in Visual Basic is register the converters into the serializer. You can't call the Read methods of the converters from Visual Basic code.
  • Overloads of other APIs that include a ReadOnlySpan<T> type. Most methods include overloads that use String instead of ReadOnlySpan.

These restrictions are in place because ref structs cannot be used safely without language support, even when just 'passing data through.' Subverting this error will result in Visual Basic code that can corrupt memory and should not be done.

Namespaces

The System.Text.Json namespace contains all the entry points and the main types. The System.Text.Json.Serialization namespace contains attributes and APIs for advanced scenarios and customization specific to serialization and deserialization. The code examples shown in this article require using directives for one or both of these namespaces:

Important

Attributes from the System.Runtime.Serialization namespace aren't supported in System.Text.Json.

How to write .NET objects as JSON (serialize)

To write JSON to a string or to a file, call the JsonSerializer.Serialize method.

The following example creates JSON as a string:

The JSON output is minified (whitespace, indentation, and new-line characters are removed) by default.

The following example uses synchronous code to create a JSON file:

The following example uses asynchronous code to create a JSON file:

The preceding examples use type inference for the type being serialized. An overload of Serialize() takes a generic type parameter:

Serialization example

Here's an example showing how a class that contains collection properties and a user-defined type is serialized:

Serialize to UTF-8

Serializing to a UTF-8 byte array is about 5-10% faster than using the string-based methods. The difference is because the bytes (as UTF-8) don't need to be converted to strings (UTF-16).

To serialize to a UTF-8 byte array, call the JsonSerializer.SerializeToUtf8Bytes method:

A Serialize overload that takes a Utf8JsonWriter is also available.

Serialization behavior

  • By default, all public properties are serialized. You can specify properties to ignore.
  • The default encoder escapes non-ASCII characters, HTML-sensitive characters within the ASCII-range, and characters that must be escaped according to the RFC 8259 JSON spec.
  • By default, JSON is minified. You can pretty-print the JSON.
  • By default, casing of JSON names matches the .NET names. You can customize JSON name casing.
  • By default, circular references are detected and exceptions thrown. You can preserve references and handle circular references.
  • By default, fields are ignored. You can include fields.

When you use System.Text.Json indirectly in an ASP.NET Core app, some default behaviors are different. For more information, see Web defaults for JsonSerializerOptions.

Class
  • By default, all public properties are serialized. You can specify properties to ignore.
  • The default encoder escapes non-ASCII characters, HTML-sensitive characters within the ASCII-range, and characters that must be escaped according to the RFC 8259 JSON spec.
  • By default, JSON is minified. You can pretty-print the JSON.
  • By default, casing of JSON names matches the .NET names. You can customize JSON name casing.
  • Circular references are detected and exceptions thrown.
  • Fields are ignored.

Supported types include:

  • .NET primitives that map to JavaScript primitives, such as numeric types, strings, and Boolean.
  • User-defined plain old CLR objects (POCOs).
  • One-dimensional and jagged arrays (T[][]).
  • Collections and dictionaries from the following namespaces.
  • .NET primitives that map to JavaScript primitives, such as numeric types, strings, and Boolean.
  • User-defined plain old CLR objects (POCOs).
  • One-dimensional and jagged arrays (ArrayName[][]).
  • Dictionary<string,TValue> where TValue is object, JsonElement, or a POCO.
  • Collections from the following namespaces.
Typescript deserialize json to class code

For more information, see Supported collection types in System.Text.Json.

You can implement custom converters to handle additional types or to provide functionality that isn't supported by the built-in converters.

How to read JSON as .NET objects (deserialize)

To deserialize from a string or a file, call the JsonSerializer.Deserialize method.

The following example shows how to deserialize a JSON string:

To deserialize from a file by using synchronous code, read the file into a string, as shown in the following example:

To deserialize from a file by using asynchronous code, call the DeserializeAsync method:

Tip

If you have JSON that you want to deserialize, and you don't have the class to deserialize it into, you have options other than manually creating the class that you need:

  • Deserialize into a JSON DOM (document object model) and extract what you need from the DOM.

    The DOM lets you navigate to a subsection of a JSON payload and deserialize a single value, a custom type, or an array. For information about the JsonNode DOM in .NET 6, see Deserialize subsections of a JSON payload. For information about the JsonDocument DOM, see How to search a JsonDocument and JsonElement for sub-elements.

  • Use the Utf8JsonReader directly.

  • Use Visual Studio 2019 to automatically generate the class you need:

    • Copy the JSON that you need to deserialize.
    • Create a class file and delete the template code.
    • Choose Edit > Paste Special > Paste JSON as Classes.The result is a class that you can use for your deserialization target.

Deserialize from UTF-8

To deserialize from UTF-8, call a JsonSerializer.Deserialize overload that takes a ReadOnlySpan<byte> or a Utf8JsonReader, as shown in the following examples. The examples assume the JSON is in a byte array named jsonUtf8Bytes.

Deserialization behavior

The following behaviors apply when deserializing JSON:

Typescript Deserialize Json To ClassTypescript parse json to class
  • By default, property name matching is case-sensitive. You can specify case-insensitivity.
  • If the JSON contains a value for a read-only property, the value is ignored and no exception is thrown.
  • Non-public constructors are ignored by the serializer.
  • Deserialization to immutable objects or properties that don't have public set accessors is supported. See Immutable types and Records.
  • By default, enums are supported as numbers. You can serialize enum names as strings.
  • By default, fields are ignored. You can include fields.
  • By default, comments or trailing commas in the JSON throw exceptions. You can allow comments and trailing commas.
  • The default maximum depth is 64.

When you use System.Text.Json indirectly in an ASP.NET Core app, some default behaviors are different. For more information, see Web defaults for JsonSerializerOptions.

  • By default, property name matching is case-sensitive. You can specify case-insensitivity. ASP.NET Core apps specify case-insensitivity by default.
  • If the JSON contains a value for a read-only property, the value is ignored and no exception is thrown.
  • A parameterless constructor, which can be public, internal, or private, is used for deserialization.
  • Deserialization to immutable objects or properties that don't have public set accessors isn't supported.
  • By default, enums are supported as numbers. You can serialize enum names as strings.
  • Fields aren't supported.
  • By default, comments or trailing commas in the JSON throw exceptions. You can allow comments and trailing commas.
  • The default maximum depth is 64.

When you use System.Text.Json indirectly in an ASP.NET Core app, some default behaviors are different. For more information, see Web defaults for JsonSerializerOptions.

You can implement custom converters to provide functionality that isn't supported by the built-in converters.

Serialize to formatted JSON

To pretty-print the JSON output, set JsonSerializerOptions.WriteIndented to true:

If you use JsonSerializerOptions repeatedly with the same options, don't create a new JsonSerializerOptions instance each time you use it. Reuse the same instance for every call. For more information, see Reuse JsonSerializerOptions instances.

Include fields

Use the JsonSerializerOptions.IncludeFields global setting or the [JsonInclude] attribute to include fields when serializing or deserializing, as shown in the following example:

To ignore read-only fields, use the JsonSerializerOptions.IgnoreReadOnlyFields global setting.

Typescript Deserialize Json To Class 9

Fields are not supported in System.Text.Json in .NET Core 3.1. Custom converters can provide this functionality.

HttpClient and HttpContent extension methods

Serializing and deserializing JSON payloads from the network are common operations. Extension methods on HttpClient and HttpContent let you do these operations in a single line of code. These extension methods use web defaults for JsonSerializerOptions.

The following example illustrates use of HttpClientJsonExtensions.GetFromJsonAsync and HttpClientJsonExtensions.PostAsJsonAsync:

Typescript Parse Json To Class

There are also extension methods for System.Text.Json on HttpContent.

Typescript Deserialize Json To Class C

Extension methods on HttpClient and HttpContent are not available in System.Text.Json in .NET Core 3.1.

Typescript Deserialize Json To Class Converter

See also