我从AJAX调用REST服务器接收JSON对象。此对象具有与我的TypeScript类匹配的属性名称(这是this question的后续内容)。
初始化它的最佳方法是什么?我认为this不会起作用,因为类(& JSON对象)的成员是对象列表和成员类,而这些类的成员是列表和/或类。
但我更喜欢一种查找成员名称并将其分配的方法,创建列表并根据需要实例化类,因此我不必为每个类中的每个成员编写显式代码(有很多! )
答案 0 :(得分:168)
这是一些快速拍摄,以显示几种不同的方式。它们绝不是“完整的”,作为免责声明,我不认为这样做是个好主意。此外,代码不是太干净,因为我只是很快地将它们拼凑在一起。
另外作为注释:当然,可反序列化的类需要具有默认构造函数,就像我知道任何类型的反序列化的所有其他语言一样。当然,如果你调用一个没有参数的非默认构造函数,Javascript就不会抱怨,但是那个类更适合它(加上,它实际上不是“typescripty方式”)。
这种方法的问题主要是任何成员的名称必须与其类匹配。这会自动将您限制为每个班级相同类型的一名成员,并违反了一些良好做法规则。我强烈反对这一点,但只是在这里列出,因为这是我写这个答案时的第一个“草案”(这也是为什么名字是“Foo”等)。
module Environment {
export class Sub {
id: number;
}
export class Foo {
baz: number;
Sub: Sub;
}
}
function deserialize(json, environment, clazz) {
var instance = new clazz();
for(var prop in json) {
if(!json.hasOwnProperty(prop)) {
continue;
}
if(typeof json[prop] === 'object') {
instance[prop] = deserialize(json[prop], environment, environment[prop]);
} else {
instance[prop] = json[prop];
}
}
return instance;
}
var json = {
baz: 42,
Sub: {
id: 1337
}
};
var instance = deserialize(json, Environment, Environment.Foo);
console.log(instance);
为了摆脱选项#1中的问题,我们需要获得JSON对象中节点类型的某种信息。问题是在Typescript中,这些是编译时构造,我们在运行时需要它们 - 但运行时对象在设置之前根本不知道它们的属性。
一种方法是让课程知道他们的名字。但是,您也需要在JSON中使用此属性。实际上,你只需在json中需要它:
module Environment {
export class Member {
private __name__ = "Member";
id: number;
}
export class ExampleClass {
private __name__ = "ExampleClass";
mainId: number;
firstMember: Member;
secondMember: Member;
}
}
function deserialize(json, environment) {
var instance = new environment[json.__name__]();
for(var prop in json) {
if(!json.hasOwnProperty(prop)) {
continue;
}
if(typeof json[prop] === 'object') {
instance[prop] = deserialize(json[prop], environment);
} else {
instance[prop] = json[prop];
}
}
return instance;
}
var json = {
__name__: "ExampleClass",
mainId: 42,
firstMember: {
__name__: "Member",
id: 1337
},
secondMember: {
__name__: "Member",
id: -1
}
};
var instance = deserialize(json, Environment);
console.log(instance);
如上所述,类成员的类型信息在运行时不可用 - 除非我们使其可用。我们只需要为非原始成员执行此操作,我们很高兴:
interface Deserializable {
getTypes(): Object;
}
class Member implements Deserializable {
id: number;
getTypes() {
// since the only member, id, is primitive, we don't need to
// return anything here
return {};
}
}
class ExampleClass implements Deserializable {
mainId: number;
firstMember: Member;
secondMember: Member;
getTypes() {
return {
// this is the duplication so that we have
// run-time type information :/
firstMember: Member,
secondMember: Member
};
}
}
function deserialize(json, clazz) {
var instance = new clazz(),
types = instance.getTypes();
for(var prop in json) {
if(!json.hasOwnProperty(prop)) {
continue;
}
if(typeof json[prop] === 'object') {
instance[prop] = deserialize(json[prop], types[prop]);
} else {
instance[prop] = json[prop];
}
}
return instance;
}
var json = {
mainId: 42,
firstMember: {
id: 1337
},
secondMember: {
id: -1
}
};
var instance = deserialize(json, ExampleClass);
console.log(instance);
Update 01/03/2016:正如@GameAlchemist在评论中指出的那样,从Typescript 1.7开始,下面描述的解决方案可以使用类/属性装饰器以更好的方式编写。
序列化总是一个问题,在我看来,最好的方法是一种不是最短的方式。在所有选项中,这是我更喜欢的,因为类的作者可以完全控制反序列化对象的状态。如果我不得不猜测,我会说所有其他选项,迟早会让你遇到麻烦(除非Javascript提出了一种原生方式来解决这个问题)。
真的,下面的例子没有做到灵活正义。它确实只是复制了类的结构。不过,你必须要记住的是,该类可以完全控制使用它想要控制整个类状态的任何类型的JSON(你可以计算等等)。
interface Serializable<T> {
deserialize(input: Object): T;
}
class Member implements Serializable<Member> {
id: number;
deserialize(input) {
this.id = input.id;
return this;
}
}
class ExampleClass implements Serializable<ExampleClass> {
mainId: number;
firstMember: Member;
secondMember: Member;
deserialize(input) {
this.mainId = input.mainId;
this.firstMember = new Member().deserialize(input.firstMember);
this.secondMember = new Member().deserialize(input.secondMember);
return this;
}
}
var json = {
mainId: 42,
firstMember: {
id: 1337
},
secondMember: {
id: -1
}
};
var instance = new ExampleClass().deserialize(json);
console.log(instance);
答案 1 :(得分:31)
TLDR:TypedJSON(工作概念验证)
此问题复杂性的根源在于我们需要使用仅存在于编译时的类型信息在运行时反序列化JSON。这要求在运行时以某种方式提供类型信息。
幸运的是,这可以通过decorators和ReflectDecorators以非常优雅和健壮的方式解决:
通过ReflectDecorators和属性修饰符的组合,可以轻松记录有关属性的类型信息。这种方法的基本实施将是:
function JsonMember(target: any, propertyKey: string) {
var metadataFieldKey = "__propertyTypes__";
// Get the already recorded type-information from target, or create
// empty object if this is the first property.
var propertyTypes = target[metadataFieldKey] || (target[metadataFieldKey] = {});
// Get the constructor reference of the current property.
// This is provided by TypeScript, built-in (make sure to enable emit
// decorator metadata).
propertyTypes[propertyKey] = Reflect.getMetadata("design:type", target, propertyKey);
}
对于任何给定的属性,上面的代码片段会将属性的构造函数的引用添加到类原型上的隐藏__propertyTypes__
属性。例如:
class Language {
@JsonMember // String
name: string;
@JsonMember// Number
level: number;
}
class Person {
@JsonMember // String
name: string;
@JsonMember// Language
language: Language;
}
就是这样,我们在运行时拥有所需的类型信息,现在可以对其进行处理。
我们首先需要使用Object
获取JSON.parse
实例 - 之后,我们可以遍历__propertyTypes__
(上面收集的)中的entires并相应地实例化所需的属性。必须指定根对象的类型,以便反序列化器具有起始点。
同样,这种方法的简单实现将是:
function deserialize<T>(jsonObject: any, Constructor: { new (): T }): T {
if (!Constructor || !Constructor.prototype.__propertyTypes__ || !jsonObject || typeof jsonObject !== "object") {
// No root-type with usable type-information is available.
return jsonObject;
}
// Create an instance of root-type.
var instance: any = new Constructor();
// For each property marked with @JsonMember, do...
Object.keys(Constructor.prototype.__propertyTypes__).forEach(propertyKey => {
var PropertyType = Constructor.prototype.__propertyTypes__[propertyKey];
// Deserialize recursively, treat property type as root-type.
instance[propertyKey] = deserialize(jsonObject[propertyKey], PropertyType);
});
return instance;
}
var json = '{ "name": "John Doe", "language": { "name": "en", "level": 5 } }';
var person: Person = deserialize(JSON.parse(json), Person);
上述想法具有通过期望的类型(对于复杂/对象值)而不是JSON中存在的类型进行反序列化的巨大优势。如果需要Person
,那么它是创建的Person
实例。通过对原始类型和数组采取一些额外的安全措施,可以使这种方法安全,抵御任何恶意JSON。
但是,如果你现在很高兴解决方案 简单,我有一些坏消息:需要采取大量数量的边缘情况照顾。其中只有一部分是:
如果你不想摆弄所有这些(我打赌你不这样做),我很乐意推荐使用这种方法的概念验证的实验版,{{3 - 我为解决这个问题而创建的,这是我每天面对的一个问题。
由于装饰器仍然被认为是实验性的,我不建议将它用于生产用途,但到目前为止,它对我有好处。
答案 2 :(得分:31)
您可以使用Object.assign
我不知道何时添加,我目前正在使用Typescript 2.0.2,这似乎是ES6功能。
client.fetch( '' ).then( response => {
return response.json();
} ).then( json => {
let hal : HalJson = Object.assign( new HalJson(), json );
log.debug( "json", hal );
此处HalJson
export class HalJson {
_links: HalLinks;
}
export class HalLinks implements Links {
}
export interface Links {
readonly [text: string]: Link;
}
export interface Link {
readonly href: URL;
}
这里有铬说的是
HalJson {_links: Object}
_links
:
Object
public
:
Object
href
:
"http://localhost:9000/v0/public
所以你可以看到它没有递归地分配
答案 3 :(得分:11)
我一直在用这个人来完成这项工作:https://github.com/weichx/cerialize
它非常简单但功能强大。它支持:
示例:
class Tree {
@deserialize public species : string;
@deserializeAs(Leaf) public leafs : Array<Leaf>; //arrays do not need extra specifications, just a type.
@deserializeAs(Bark, 'barkType') public bark : Bark; //using custom type and custom key name
@deserializeIndexable(Leaf) public leafMap : {[idx : string] : Leaf}; //use an object as a map
}
class Leaf {
@deserialize public color : string;
@deserialize public blooming : boolean;
@deserializeAs(Date) public bloomedAt : Date;
}
class Bark {
@deserialize roughness : number;
}
var json = {
species: 'Oak',
barkType: { roughness: 1 },
leafs: [ {color: 'red', blooming: false, bloomedAt: 'Mon Dec 07 2015 11:48:20 GMT-0500 (EST)' } ],
leafMap: { type1: { some leaf data }, type2: { some leaf data } }
}
var tree: Tree = Deserialize(json, Tree);
答案 4 :(得分:3)
我创建了一个生成TypeScript接口和运行时“类型映射”的工具,用于根据JSON.parse
的结果执行运行时类型检查:ts.quicktype.io
例如,给定这个JSON:
{
"name": "David",
"pets": [
{
"name": "Smoochie",
"species": "rhino"
}
]
}
quicktype生成以下TypeScript接口并输入map:
export interface Person {
name: string;
pets: Pet[];
}
export interface Pet {
name: string;
species: string;
}
const typeMap: any = {
Person: {
name: "string",
pets: array(object("Pet")),
},
Pet: {
name: "string",
species: "string",
},
};
然后我们针对类型映射检查JSON.parse
的结果:
export function fromJson(json: string): Person {
return cast(JSON.parse(json), object("Person"));
}
我遗漏了一些代码,但您可以尝试quicktype了解详细信息。
答案 5 :(得分:3)
这似乎是最易于维护的方法:添加一个构造函数,该构造函数将json结构作为参数,并扩展json对象。这样你就可以将json结构解析为整个应用程序模型。
无需在构造函数中创建接口或列出属性。
export class Company
{
Employees : Employee[];
constructor( jsonData: any )
{
jQuery.extend( this, jsonData);
// apply the same principle to linked objects:
if ( jsonData.Employees )
this.Employees = jQuery.map( jsonData.Employees , (emp) => {
return new Employee ( emp ); });
}
calculateSalaries() : void { .... }
}
export class Employee
{
name: string;
salary: number;
city: string;
constructor( jsonData: any )
{
jQuery.extend( this, jsonData);
// case where your object's property does not match the json's:
this.city = jsonData.town;
}
}
在您收到公司计算工资的ajax回调中:
onReceiveCompany( jsonCompany : any )
{
let newCompany = new Company( jsonCompany );
// call the methods on your newCompany object ...
newCompany.calculateSalaries()
}
答案 6 :(得分:1)
上面描述的第四个选项是一个简单而好的方法,在必须处理类层次结构的情况下必须与第二个选项结合使用,例如成员列表,它是任何出现的成员超级类的子类,例如,Director扩展成员或学生扩展成员。在这种情况下,您必须以json格式提供子类类型
答案 7 :(得分:1)
对于简单对象,我喜欢这种方法:
class Person {
constructor(
public id: String,
public name: String,
public title: String) {};
static deserialize(input:any): Person {
return new Person(input.id, input.name, input.title);
}
}
var person = Person.deserialize({id: 'P123', name: 'Bob', title: 'Mr'});
利用在构造函数中定义属性的能力,可以使其简洁明了。
这将为您提供一个类型化的对象(与使用Object.assign或某些变体的所有答案(为您提供一个对象)相对),并且不需要外部库或修饰符。
答案 8 :(得分:1)
JQuery .extend为您做到这一点:
var mytsobject = new mytsobject();
var newObj = {a:1,b:2};
$.extend(mytsobject, newObj); //mytsobject will now contain a & b
答案 9 :(得分:0)
使用工厂的另一个选择
export class A {
id: number;
date: Date;
bId: number;
readonly b: B;
}
export class B {
id: number;
}
export class AFactory {
constructor(
private readonly createB: BFactory
) { }
create(data: any): A {
const createB = this.createB.create;
return Object.assign(new A(),
data,
{
get b(): B {
return createB({ id: data.bId });
},
date: new Date(data.date)
});
}
}
export class BFactory {
create(data: any): B {
return Object.assign(new B(), data);
}
}
https://github.com/MrAntix/ts-deserialize
像这样使用
import { A, B, AFactory, BFactory } from "./deserialize";
// create a factory, simplified by DI
const aFactory = new AFactory(new BFactory());
// get an anon js object like you'd get from the http call
const data = { bId: 1, date: '2017-1-1' };
// create a real model from the anon js object
const a = aFactory.create(data);
// confirm instances e.g. dates are Dates
console.log('a.date is instanceof Date', a.date instanceof Date);
console.log('a.b is instanceof B', a.b instanceof B);
答案 10 :(得分:0)
也许不是真实的,但简单的解决方案:
interface Bar{
x:number;
y?:string;
}
var baz:Bar = JSON.parse(jsonString);
alert(baz.y);
也为困难的依赖工作!!!
答案 11 :(得分:0)
我为此找到的最好的是class-transformer。 github.com/typestack/class-transformer
这就是您的使用方式:
某些班级:
export class Foo {
name: string;
@Type(() => Bar)
bar: Bar;
public someFunction = (test: string): boolean => {
...
}
}
import { plainToClass } from 'class-transformer';
export class SomeService {
anyFunction() {
u = plainToClass(Foo, JSONobj);
}
如果使用@Type装饰器,也会创建嵌套属性。
答案 12 :(得分:0)
我个人更喜欢@IngoBürk的选项#3。 并且我改进了他的代码,以支持复杂数据数组和原始数据数组。
interface IDeserializable {
getTypes(): Object;
}
class Utility {
static deserializeJson<T>(jsonObj: object, classType: any): T {
let instanceObj = new classType();
let types: IDeserializable;
if (instanceObj && instanceObj.getTypes) {
types = instanceObj.getTypes();
}
for (var prop in jsonObj) {
if (!(prop in instanceObj)) {
continue;
}
let jsonProp = jsonObj[prop];
if (this.isObject(jsonProp)) {
instanceObj[prop] =
types && types[prop]
? this.deserializeJson(jsonProp, types[prop])
: jsonProp;
} else if (this.isArray(jsonProp)) {
instanceObj[prop] = [];
for (let index = 0; index < jsonProp.length; index++) {
const elem = jsonProp[index];
if (this.isObject(elem) && types && types[prop]) {
instanceObj[prop].push(this.deserializeJson(elem, types[prop]));
} else {
instanceObj[prop].push(elem);
}
}
} else {
instanceObj[prop] = jsonProp;
}
}
return instanceObj;
}
//#region ### get types ###
/**
* check type of value be string
* @param {*} value
*/
static isString(value: any) {
return typeof value === "string" || value instanceof String;
}
/**
* check type of value be array
* @param {*} value
*/
static isNumber(value: any) {
return typeof value === "number" && isFinite(value);
}
/**
* check type of value be array
* @param {*} value
*/
static isArray(value: any) {
return value && typeof value === "object" && value.constructor === Array;
}
/**
* check type of value be object
* @param {*} value
*/
static isObject(value: any) {
return value && typeof value === "object" && value.constructor === Object;
}
/**
* check type of value be boolean
* @param {*} value
*/
static isBoolean(value: any) {
return typeof value === "boolean";
}
//#endregion
}
// #region ### Models ###
class Hotel implements IDeserializable {
id: number = 0;
name: string = "";
address: string = "";
city: City = new City(); // complex data
roomTypes: Array<RoomType> = []; // array of complex data
facilities: Array<string> = []; // array of primitive data
// getter example
get nameAndAddress() {
return `${this.name} ${this.address}`;
}
// function example
checkRoom() {
return true;
}
// this function will be use for getting run-time type information
getTypes() {
return {
city: City,
roomTypes: RoomType
};
}
}
class RoomType implements IDeserializable {
id: number = 0;
name: string = "";
roomPrices: Array<RoomPrice> = [];
// getter example
get totalPrice() {
return this.roomPrices.map(x => x.price).reduce((a, b) => a + b, 0);
}
getTypes() {
return {
roomPrices: RoomPrice
};
}
}
class RoomPrice {
price: number = 0;
date: string = "";
}
class City {
id: number = 0;
name: string = "";
}
// #endregion
// #region ### test code ###
var jsonObj = {
id: 1,
name: "hotel1",
address: "address1",
city: {
id: 1,
name: "city1"
},
roomTypes: [
{
id: 1,
name: "single",
roomPrices: [
{
price: 1000,
date: "2020-02-20"
},
{
price: 1500,
date: "2020-02-21"
}
]
},
{
id: 2,
name: "double",
roomPrices: [
{
price: 2000,
date: "2020-02-20"
},
{
price: 2500,
date: "2020-02-21"
}
]
}
],
facilities: ["facility1", "facility2"]
};
var hotelInstance = Utility.deserializeJson<Hotel>(jsonObj, Hotel);
console.log(hotelInstance.city.name);
console.log(hotelInstance.nameAndAddress); // getter
console.log(hotelInstance.checkRoom()); // function
console.log(hotelInstance.roomTypes[0].totalPrice); // getter
// #endregion
答案 13 :(得分:0)
我的方法略有不同。我不会将属性复制到新实例中,而只是更改现有POJO的原型(可能无法在较旧的浏览器上很好地工作)。每个类负责提供一个SetPrototypes方法来设置任何子对象的原型,而子对象又提供自己的SetPrototypes方法。
(我还使用_Type属性获取未知对象的类名,但在此处可以忽略)
class ParentClass
{
public ID?: Guid;
public Child?: ChildClass;
public ListOfChildren?: ChildClass[];
/**
* Set the prototypes of all objects in the graph.
* Used for recursive prototype assignment on a graph via ObjectUtils.SetPrototypeOf.
* @param pojo Plain object received from API/JSON to be given the class prototype.
*/
private static SetPrototypes(pojo: ParentClass): void
{
ObjectUtils.SetPrototypeOf(pojo.Child, ChildClass);
ObjectUtils.SetPrototypeOfAll(pojo.ListOfChildren, ChildClass);
}
}
class ChildClass
{
public ID?: Guid;
public GrandChild?: GrandChildClass;
/**
* Set the prototypes of all objects in the graph.
* Used for recursive prototype assignment on a graph via ObjectUtils.SetPrototypeOf.
* @param pojo Plain object received from API/JSON to be given the class prototype.
*/
private static SetPrototypes(pojo: ChildClass): void
{
ObjectUtils.SetPrototypeOf(pojo.GrandChild, GrandChildClass);
}
}
这是ObjectUtils.ts:
/**
* ClassType lets us specify arguments as class variables.
* (where ClassType == window[ClassName])
*/
type ClassType = { new(...args: any[]): any; };
/**
* The name of a class as opposed to the class itself.
* (where ClassType == window[ClassName])
*/
type ClassName = string & {};
abstract class ObjectUtils
{
/**
* Set the prototype of an object to the specified class.
*
* Does nothing if source or type are null.
* Throws an exception if type is not a known class type.
*
* If type has the SetPrototypes method then that is called on the source
* to perform recursive prototype assignment on an object graph.
*
* SetPrototypes is declared private on types because it should only be called
* by this method. It does not (and must not) set the prototype of the object
* itself - only the protoypes of child properties, otherwise it would cause a
* loop. Thus a public method would be misleading and not useful on its own.
*
* https://stackoverflow.com/questions/9959727/proto-vs-prototype-in-javascript
*/
public static SetPrototypeOf(source: any, type: ClassType | ClassName): any
{
let classType = (typeof type === "string") ? window[type] : type;
if (!source || !classType)
{
return source;
}
// Guard/contract utility
ExGuard.IsValid(classType.prototype, "type", <any>type);
if ((<any>Object).setPrototypeOf)
{
(<any>Object).setPrototypeOf(source, classType.prototype);
}
else if (source.__proto__)
{
source.__proto__ = classType.prototype.__proto__;
}
if (typeof classType["SetPrototypes"] === "function")
{
classType["SetPrototypes"](source);
}
return source;
}
/**
* Set the prototype of a list of objects to the specified class.
*
* Throws an exception if type is not a known class type.
*/
public static SetPrototypeOfAll(source: any[], type: ClassType): void
{
if (!source)
{
return;
}
for (var i = 0; i < source.length; i++)
{
this.SetPrototypeOf(source[i], type);
}
}
}
用法:
let pojo = SomePlainOldJavascriptObjectReceivedViaAjax;
let parentObject = ObjectUtils.SetPrototypeOf(pojo, ParentClass);
// parentObject is now a proper ParentClass instance
答案 14 :(得分:0)
这是我的方法(非常简单):
const jsonObj: { [key: string]: any } = JSON.parse(jsonStr);
for (const key in jsonObj) {
if (!jsonObj.hasOwnProperty(key)) {
continue;
}
console.log(key); // Key
console.log(jsonObj[key]); // Value
// Your logic...
}
答案 15 :(得分:-1)
你可以这样做
export interface Instance {
id?:string;
name?:string;
type:string;
}
和
var instance: Instance = <Instance>({
id: null,
name: '',
type: ''
});
答案 16 :(得分:-1)
**model.ts**
export class Item {
private key: JSON;
constructor(jsonItem: any) {
this.key = jsonItem;
}
}
**service.ts**
import { Item } from '../model/items';
export class ItemService {
items: Item;
constructor() {
this.items = new Item({
'logo': 'Logo',
'home': 'Home',
'about': 'About',
'contact': 'Contact',
});
}
getItems(): Item {
return this.items;
}
}