在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:appvision-gmbh/json2typescript开源软件地址:https://github.com/appvision-gmbh/json2typescript开源编程语言:TypeScript 99.3%开源软件介绍:json2typescriptIn Angular applications, everyone consumes JSON API's from an external source. Type checking and object mapping is only possible in TypeScript, but not in the JavaScript runtime. As the API may change at any point, it is important for larger projects to verify the consumed data. json2typescript is a small package containing a helper class that maps JSON objects to an instance of a TypeScript class. After compiling to JavaScript, the result will still be an instance of this class. One big advantage of this approach is, that you can also use methods of this class. With json2typescript, only a simple function call is necessary, as demonstrated in this TypeScript snippet: // Assume that you have a class named User defined at some point
// Assume that you get a JSON string from a webservice
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{ ... }
ChangelogSee the changelog in the separate file for bug fixes, new features and breaking changes: Changelog
Getting startedRequirementsWe developed json2typescript for Angular 2+ and Ionic 2+. In this document, we only cover this use case. However, you may use our package for pure TypeScript or even JavaScript applications. Setup a Test ApplicationWe recommend to use the official angular cli tool in order to set up a new Angular project. Then, all you need to do is type the following into your operating system's terminal: ng new testApplication
cd testApplication
npm install json2typescript Our package makes use of TypeScript decorators. If not done already, please activate them in your tsconfig.json
under {
"compilerOptions": {
[
...
]
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
[...]
}
Now you are ready to use the package. Mapping exampleIn order to use the json2typescript package, all you need to do is write decorators and import the package. The following things need to be done if you would like to map JSON to existing classes:
See below an example, so you can learn from it how json2typescript works best. Assuming that you have created the testApplication in the step before and installed json2typescript as suggested, create a class in a new file city.ts with the following content: 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 use 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<string>
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 + ".");
}
} Now create a file country.ts with the following content: 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[] = [];
} Then navigate to the file app.component.ts and add the following code: 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((<Error>e));
}
} Play around with the JSON to provocate exceptions when deserializing the object. Important notesAvoid circular dependencies on the classes that use Detailed referenceClass and property decoratorsDecorators should be used whenever you would like to map JSON with TypeScript data. As of now, you must not use more than one decorator per class or property. Class decoratorsThe class decorators are used infront of the class declaration and do support one parameter: @JsonObject("User")
export class User {}
First parameter: classIdentifierThe first parameter of
Property decoratorsProperty decorators are a vital part for type checking. It is important that the type in the decorator matches the TypeScript type. For class properties to be visible to the mapper they must be initialized, otherwise they are ignored.
They can be initialized using any (valid) value or @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
}
First parameter: jsonPropertyThe first parameter of Second parameter (optional): conversionOptionThe second parameter of Use of expected typeIf you would like that
See the following cheat sheet for reference:
At first, our array notation on the left looks odd. But this notation allows you to define even nested arrays. See the examples at the end of this document for more info about nesting arrays.
Adding a custom converterMore advanced users may need to use custom converters. If you want
Assume you would like to transform @JsonObject("User")
export class User {
@JsonProperty("birthdate", DateConverter)
birthdate: Date = new Date();
} Third parameter (optional): convertingModeThe third parameter of See also the property The values should be used as follows:
Handling null, undefined and absent valuesBe careful when handling special values as By default, The global setting of The following table explains the difference between the three property converting modes:
As shown in this table, a property with the default setting
Important notes
More about the array syntax
Custom converter decoratorsIn some cases, you may need to make custom conversion between JSON objects and TypeScript objects. You can define custom converters like this: @JsonConverter
class DateConverter implements JsonCustomConvert<Date> {
serialize(date: Date): any {
return date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
}
deserialize(date: any): Date {
return new Date(date);
}
}
Assume that in your JSON you have a date in a standardized format, such as 全部评论
专题导读
上一篇:feitnomore/hyperledger-fabric-kubernetes: Blockchain Solution with Hyperledger F ...发布时间:2022-07-09下一篇:Bowserinator/Periodic-Table-JSON: A json of the entire periodic table.发布时间:2022-07-08热门推荐
热门话题
阅读排行榜
|
请发表评论