### Install json2typescript with Angular CLI Source: https://github.com/appvision-gmbh/json2typescript/blob/master/README.md Install the json2typescript package using npm after setting up a new Angular project with the Angular CLI. ```sh ng new testApplication cd testApplication npm install json2typescript ``` -------------------------------- ### User Class with Lazy Loading Source: https://github.com/appvision-gmbh/json2typescript/blob/master/README.md Example of a User class using json2typescript decorators with lazy loading. Use string identifiers for nested classes to avoid circular dependencies. ```typescript import { Team } from "./team"; @JsonObject("User") export class User { @JsonProperty("teams", [Team]) team: Team[] = []; } ``` -------------------------------- ### Class Decorator Example Source: https://github.com/appvision-gmbh/json2typescript/blob/master/README.md Use the @JsonObject decorator at the beginning of a class declaration to identify it. The parameter must be a unique string identifier for the class. ```typescript import { JsonObject } from "json2typescript"; @JsonObject("User") export class User {} ``` -------------------------------- ### Property Decorator Example Source: https://github.com/appvision-gmbh/json2typescript/blob/master/README.md Use the @JsonProperty decorator for class properties to enable type checking and mapping. Properties must be initialized with a valid value or undefined to be recognized by the mapper. ```typescript import { JsonObject, JsonProperty } from "json2typescript"; @JsonObject("User") export class User { // A correct example @JsonProperty("name", String, false) name: string = ""; // An incorrect example @JsonProperty("alias", string, false) // Wrong type: Must use String instead. alias: string = ""; // An incorrect example @JsonProperty("expertise", String, false) expertise: string; // No initialization: Property will be ignored without visible exception } ``` -------------------------------- ### Team Class with Lazy Loading Source: https://github.com/appvision-gmbh/json2typescript/blob/master/README.md Example of a Team class using json2typescript decorators with lazy loading. Use string identifiers for nested classes to avoid circular dependencies. ```typescript import { User } from "./user"; @JsonObject("Team") export class Team { @JsonProperty("users", [User]) user: User[] = []; } ``` -------------------------------- ### Using a Custom DateConverter with @JsonProperty Source: https://github.com/appvision-gmbh/json2typescript/blob/master/README.md This example shows how to use a custom converter (DateConverter) with the @JsonProperty decorator to map a string from JSON to a TypeScript Date object. Ensure the converter class implements JsonCustomConvert and is decorated with @JsonConverter. ```typescript @JsonObject("User") export class User { @JsonProperty("birthdate", DateConverter) birthdate: Date = new Date(); } ``` -------------------------------- ### Enable Decorators in tsconfig.json Source: https://github.com/appvision-gmbh/json2typescript/blob/master/README.md Configure your tsconfig.json file to enable experimental decorators and emit decorator metadata, which are required by json2typescript. ```json { "compilerOptions": { "experimentalDecorators": true, "emitDecoratorMetadata": true, } } ``` -------------------------------- ### registerClasses(...classReferences: { new(): any }[]) Source: https://github.com/appvision-gmbh/json2typescript/blob/master/README.md Registers one or more classes for use with lazy-loading and the discriminator feature. ```APIDOC ## registerClasses(...classReferences: { new(): any }[]) ### Description Registers a list of classes to be used with lazy-loading and in the discriminator feature. This is necessary when these advanced features are utilized. ### Parameters #### Path Parameters - **classReferences** ({ new(): any }[]) - Required - A variable number of class constructors to register. ``` -------------------------------- ### Configure JsonConvert for Discriminator Feature Source: https://github.com/appvision-gmbh/json2typescript/blob/master/README.md Set up a JsonConvert instance to enable and configure the discriminator feature. This involves enabling the feature, setting the discriminator property name, and registering the relevant classes. ```typescript // Set up json convert let jsonConvert: JsonConvert = new JsonConvert(); jsonConvert.useDiscriminator = true; // enable the discriminator jsonConvert.discriminatorPropertyName = "$type"; // this is the property name jsonConvert.registerClasses(User); // register all classes ``` -------------------------------- ### Define a Custom Date Converter Source: https://github.com/appvision-gmbh/json2typescript/blob/master/README.md Implement a custom converter for Date objects by extending JsonCustomConvert. Ensure the generic type matches the serialize and deserialize methods. Import JsonConverter from json2typescript. ```typescript @JsonConverter class DateConverter implements JsonCustomConvert { serialize(date: Date): any { return date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate(); } deserialize(date: any): Date { return new Date(date); } } ``` -------------------------------- ### Register Classes for Lazy-Loading/Discriminator Source: https://github.com/appvision-gmbh/json2typescript/blob/master/README.md Use `registerClasses` to make classes available for lazy-loading and the discriminator feature. This is only necessary if these specific features are being used. ```typescript jsonConvert.registerClasses(User, Address); ``` -------------------------------- ### ungisterClasses(...classReferences: { new(): any }[]) Source: https://github.com/appvision-gmbh/json2typescript/blob/master/README.md Unregisters one or more previously registered classes. ```APIDOC ## ungisterClasses(...classReferences: { new(): any }[]) ### Description Unregisters a list of classes that were previously registered for lazy-loading or the discriminator feature. ### Parameters #### Path Parameters - **classReferences** ({ new(): any }[]) - Required - A variable number of class constructors to unregister. ``` -------------------------------- ### Deserialize JSON with Discriminator Source: https://github.com/appvision-gmbh/json2typescript/blob/master/README.md Demonstrates deserializing a JSON object using the configured JsonConvert with the discriminator feature enabled. The $type property in the JSON is used to automatically instantiate the correct class. ```typescript // Assume the following JSON object coming from your server const jsonObject: any = { "name": "Walter", "$type": "app.example.User" // the value of $type matches the @JsonObject decorator above } // This is how you would traditionally map an object // But we have enabled the discriminator functionality and registered the User class // In that case, the second parameter (User) here is ignored const user1: User = jsonConvert.deserialize(jsonObject, User); // But now you may automatically map it thanks to the $type property const user2: User = jsonConvert.deserialize(jsonObject); ``` -------------------------------- ### Serialize TypeScript to JSON Source: https://github.com/appvision-gmbh/json2typescript/blob/master/README.md Use this method to convert TypeScript objects or arrays into JSON objects or arrays. Provide a class reference to use specific `@JsonProperty` mappings. If no class reference is given, mappings from the data object's class are used. The result is an object, not a string; use `JSON.stringify()` for string output. ```typescript jsonConvert.serialize(user); ``` ```typescript jsonConvert.serialize(user, User); ``` ```typescript jsonConvert.serialize(users); ``` ```typescript jsonConvert.serialize(plainObject, User); ``` -------------------------------- ### Deserialize JSON to TypeScript Class Source: https://github.com/appvision-gmbh/json2typescript/blob/master/README.md Use this snippet to map a JSON object to a TypeScript class. Configure JsonConvert settings like operationMode and valueCheckingMode before deserialization. Ensure proper error handling for potential exceptions. ```typescript import { Component, OnInit } from '@angular/core'; import { JsonConvert, OperationMode, ValueCheckingMode } from "json2typescript" import { Country } from "./country"; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { ngOnInit() { // Define a JSON object (could come from a HTTP service, parsed with JSON.parse() if necessary) const jsonObject: any = { "countryName": "Switzerland", "cities": [ { "id": 1, "name": "Basel", "founded": -200, "beautiful": true, "data": 123, "keywords": ["Rhine", "River"] }, { "id": 1, "name": "Zurich", "founded": 0, "beautiful": false, "data": "no", "keywords": ["Limmat", "Lake"] } ] }; // Choose your settings // Check the detailed reference in the chapter "JsonConvert class properties and methods" let jsonConvert: JsonConvert = new JsonConvert(); jsonConvert.operationMode = OperationMode.LOGGING; // print some debug data jsonConvert.ignorePrimitiveChecks = false; // don't allow assigning number to string etc. jsonConvert.valueCheckingMode = ValueCheckingMode.DISALLOW_NULL; // never allow null // Map to the country class let country: Country; try { country = jsonConvert.deserializeObject(jsonObject, Country); country.cities[0].printInfo(); // prints: Basel was founded in -200 and is really beautiful! } catch (e) { console.log((e)); } } } ``` -------------------------------- ### Define City Class with json2typescript Decorators Source: https://github.com/appvision-gmbh/json2typescript/blob/master/README.md Use @JsonObject and @JsonProperty decorators to map JSON keys to class properties. Ensure class identifiers are unique. Properties must have default values. ```typescript import { JsonObject, JsonProperty } from "json2typescript"; @JsonObject("City") // Make sure "City" is a unique identifier for this class export class City { // This property has no @JsonProperty. // It will not be mapped. id: number = 123; // This maps the value of the JSON key "name" to the class property "name". // If the JSON value is not of type string (or missing), there will be an exception. @JsonProperty("name", String) name: string = ""; // This maps the JSON key "founded" to the private class property "_founded". // Note the of public getter and setter. // If the JSON value is not of type number (or missing), there will be an exception. @JsonProperty("founded", Number) private _founded: number = 0; get founded() { return this._founded; } set founded(value: number) { this._founded = value; } // This maps the JSON key "beautiful" to the class property "beautiful". // If the JSON value is not of type boolean (or missing), there will be an exception. @JsonProperty("beautiful", Boolean) beautiful: boolean = false; // This maps the JSON key "data" to the class property "data". // We are not sure about the type, so we omit the second parameter. // There will be an exception if the JSON value is missing. @JsonProperty("data") // is the same as @JsonProperty("data", Any) data: any = undefined; // This maps the JSON key "keywords" to the class property "keywords". // This is an example of a string array. Note our syntax "[String]". // In the further examples at the end of this document, you can see how to nest complex arrays. @JsonProperty("keywords", [String]) keywords: string[] = []; // or Array printInfo() { if (this.beautiful) console.log(this.name + " was founded in " + this.founded + " and is really beautiful!"); else console.log(this.name + " was founded in " + this.founded + "."); } } ``` -------------------------------- ### Partially Deserialize JSON to TypeScript Source: https://github.com/appvision-gmbh/json2typescript/blob/master/README.md Use `partialDeserialize` to convert JSON to TypeScript objects, even if some properties are missing or undefined in the source JSON. Missing properties in the result will have their default values from the TypeScript class. Avoid this method if missing properties are known in advance; configure `@JsonProperty` instead. ```typescript const user: User = jsonConvert.partialDeserialize(jsonObject); ``` ```typescript const users: User[] = jsonConvert.partialDeserialize(jsonArray); ``` ```typescript const user: User = jsonConvert.partialDeserialize(jsonObject, User); ``` -------------------------------- ### serialize(data: T | T[], classReference?: { new(): U }) Source: https://github.com/appvision-gmbh/json2typescript/blob/master/README.md Serializes a TypeScript object or array of objects to JSON. Optionally takes a class reference to use specific mapping configurations. ```APIDOC ## serialize(data: T | T[], classReference?: { new(): U }) ### Description Tries to serialize a TypeScript object or array of objects to JSON. The class for serialization can be inferred automatically or provided explicitly via `classReference`. ### Parameters #### Path Parameters - **data** (T | T[]) - Required - The TypeScript object or array of objects to serialize. - **classReference** ({ new(): U } | null) - Optional - The class constructor to use for serialization mappings. If not provided, mappings from the data object's class are used. ### Returns - **any | any[]** - The serialized JSON object or array of objects. ### Notes - The return value is a JavaScript object/array, not a JSON string. Use `JSON.stringify()` if a string is needed. - Providing a `classReference` allows overriding mappings defined on the data class, useful for serializing plain objects or subclasses. ``` -------------------------------- ### Deserialize JSON to TypeScript Object Source: https://github.com/appvision-gmbh/json2typescript/blob/master/README.md Use this snippet to map a parsed JSON object to a defined TypeScript class instance. Ensure the TypeScript class is defined and the JSON is parsed before calling deserializeObject. Error handling is recommended for production environments. ```typescript let jsonStr: string = ... ; let jsonObj: any = JSON.parse(jsonStr); // Now you can map the json object to the TypeScript object automatically let jsonConvert: JsonConvert = new JsonConvert(); let user: User = jsonConvert.deserializeObject(jsonObj, User); console.log(user); // prints User{ ... } in JavaScript runtime, not Object{ ... } ``` -------------------------------- ### Partially Serialize TypeScript to JSON Source: https://github.com/appvision-gmbh/json2typescript/blob/master/README.md Use `partialSerialize` to convert TypeScript objects to JSON, even if some properties are missing or undefined in the source. The returned JSON will not include missing properties. Avoid this method if missing properties are known in advance; configure `@JsonProperty` instead. ```typescript jsonConvert.partialSerialize(user); ``` ```typescript jsonConvert.partialSerialize(user, User); ``` -------------------------------- ### partialSerialize(data: T | T[], classReference?: { new(): U }) Source: https://github.com/appvision-gmbh/json2typescript/blob/master/README.md Serializes a TypeScript object or array to JSON, ignoring missing properties in the source data. ```APIDOC ## partialSerialize(data: T | T[], classReference?: { new(): U }) ### Description Serializes a TypeScript object or array of objects to JSON, similar to `serialize`, but does not throw an error for missing properties in the source `data`. Missing properties will not be included in the output. ### Parameters #### Path Parameters - **data** (T | T[]) - Required - The TypeScript object or array of objects to serialize. - **classReference** ({ new(): U } | null) - Optional - The class constructor to use for serialization mappings. If not provided, mappings from the data object's class are used. ### Returns - **any | any[]** - The serialized JSON object or array of objects, excluding missing properties. ### Notes - This method is useful when some properties might be undefined. For known missing properties, configuring `@JsonProperty` is recommended. ``` -------------------------------- ### Deserialize JSON to TypeScript Source: https://github.com/appvision-gmbh/json2typescript/blob/master/README.md Use this method to convert JSON objects or arrays into TypeScript objects or arrays. The `json` parameter must be an object or array, not a string; use `JSON.parse()` if you have a JSON string. The `classReference` is optional if the discriminator feature is used. ```typescript const user: User = jsonConvert.deserialize(jsonObject); ``` ```typescript const users: User[] = jsonConvert.deserialize(jsonArray); ``` ```typescript const user: User = jsonConvert.deserialize(jsonObject, User); ``` -------------------------------- ### Define Country Class with Nested City Objects Source: https://github.com/appvision-gmbh/json2typescript/blob/master/README.md Map a JSON array of objects to a TypeScript array of custom class instances using nested type mapping. ```typescript import { City } from "./city"; import { JsonObject, JsonProperty } from "json2typescript"; @JsonObject("Country") // Make sure "Country" is a unique identifier for this class export class Country { // This maps the value of the JSON key "countryName" to the class property "name". // If the JSON value is not of type string (or missing), there will be an exception. @JsonProperty("countryName", String) name: string = ""; // This maps the value of the JSON key "cities" to the class property "cities". // If the JSON value is not of type array object (or missing), there will be an exception. // There will be an exception too if the objects in the array do not match the class "City". @JsonProperty("cities", [City]) cities: City[] = []; } ``` -------------------------------- ### partialDeserialize(json: any, classReference: { new(): T } | null = null) Source: https://github.com/appvision-gmbh/json2typescript/blob/master/README.md Deserializes JSON data into a TypeScript object or array, allowing for missing properties in the source JSON. ```APIDOC ## partialDeserialize(json: any, classReference: { new(): T } | null = null) ### Description Deserializes JSON data into a TypeScript object or array of objects, similar to `deserialize`, but does not throw an error if properties are missing in the source `json`. Missing properties will be included in the result with their default values from the TypeScript class. ### Parameters #### Path Parameters - **json** (any) - Required - The JSON object or array to deserialize. Must be an object or array, not a string. - **classReference** ({ new(): T } | null) - Optional - The class constructor to use for deserialization. If null and discriminator is not used, deserialization might fail or be incomplete. ### Returns - **T | T[]** - An instance or an array of instances of the specified class reference, with missing properties populated by default values. ### Notes - This method is useful when the source JSON might not contain all properties defined in the TypeScript class. For known missing properties, configuring `@JsonProperty` is recommended. ``` -------------------------------- ### Define User Class with JsonObject Decorator Source: https://github.com/appvision-gmbh/json2typescript/blob/master/README.md Define a class with the @JsonObject decorator to be used with the discriminator feature. This decorator specifies the unique identifier for the class. ```typescript import { JsonObject, JsonProperty } from "json2typescript"; @JsonObject("app.example.User") export class User { @JsonProperty("name", String) name: string = ""; } ``` -------------------------------- ### unregisterAllClasses() Source: https://github.com/appvision-gmbh/json2typescript/blob/master/README.md Unregisters all previously registered classes. ```APIDOC ## unregisterAllClasses() ### Description Unregisters all classes that have been registered for lazy-loading and the discriminator feature. This effectively resets the class registry. ``` -------------------------------- ### Apply Custom Converter with JsonProperty Source: https://github.com/appvision-gmbh/json2typescript/blob/master/README.md Use the @JsonProperty decorator to apply a custom converter to a class property. Specify the JSON property name and the custom converter class. This ensures the property is correctly converted between JSON and TypeScript types. ```typescript @JsonObject("User") export class User { @JsonProperty("date", DateConverter) date: Date = new Date(); } ``` -------------------------------- ### deserialize(json: any, classReference: { new(): T } | null = null) Source: https://github.com/appvision-gmbh/json2typescript/blob/master/README.md Deserializes JSON data into a TypeScript object or array of objects. A class reference can be provided for mapping. ```APIDOC ## deserialize(json: any, classReference: { new(): T } | null = null) ### Description Tries to deserialize given JSON to a TypeScript object or array of objects. The `classReference` is used for mapping, and is optional if the discriminator feature is used. ### Parameters #### Path Parameters - **json** (any) - Required - The JSON object or array to deserialize. Must be an object or array, not a string. - **classReference** ({ new(): T } | null) - Optional - The class constructor to use for deserialization. If null and discriminator is not used, deserialization might fail or be incomplete. ### Returns - **T | T[]** - An instance or an array of instances of the specified class reference. ### Notes - The `json` parameter must be a JavaScript object or array. Use `JSON.parse()` first if you have a JSON string. ``` -------------------------------- ### Define Nested Arrays with Same Type in TypeScript Source: https://github.com/appvision-gmbh/json2typescript/blob/master/README.md Use this when your JSON contains nested arrays where all elements within the nested arrays are of the same type. The type definition `[[String, String], [String, String]]` can be simplified due to automatic type repetition. ```json { "jsonKeyOfWeirdKeywords": [ [ "Hello", "World" ], [ "Bye", "Earth" ] ] } ``` ```typescript @JsonObject("User") export class User { @JsonProperty("jsonKeyOfWeirdKeywords", [[String, String], [String, String]]) keywords: (string[])[] = []; } ``` -------------------------------- ### Unregister Classes Source: https://github.com/appvision-gmbh/json2typescript/blob/master/README.md Use `unregisterClasses` to remove specific classes from lazy-loading and discriminator features. `unregisterAllClasses` removes all registered classes. ```typescript jsonConvert.unregisterClasses(User); ``` ```typescript jsonConvert.unregisterAllClasses(); ``` -------------------------------- ### Define Nested Arrays with Mixed Depth and Type in TypeScript Source: https://github.com/appvision-gmbh/json2typescript/blob/master/README.md Use this when your JSON contains nested arrays with varying depths and element types. The type definition `[[String, String], Number]` accommodates a mix of nested arrays and direct values. ```json { "jsonKeyOfWeirdKeywords": [ [ "FC", "Basel" ], 1893 ] } ``` ```typescript @JsonObject("User") export class User { @JsonProperty("jsonKeyOfWeirdKeywords", [[String, String], Number]) keywords: (string[] | number)[] = []; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.