SOAP 웹 서비스의 응답을 역 직렬화해야했습니다. 먼저 기존 SOAP 클라이언트를 사용하여 반환 된 XML에서 객체를 가져온 다음 JSON 디시리얼라이저 (http://cloudmark.github.io/Json-Mapping/)를 사용하여이 객체를 원하는 실제 유형으로 비 직렬화했습니다.
반환되는 속성 중 하나가 기본 유형으로 선언되어 실제로 여러 가지 하위 유형의 인스턴스를 포함 할 수있는 문제가있었습니다.
파생 된 유형에 적용 할 클래스 데코레이터를 만들어 해결했습니다. 이 클래스 장식자는 기본 클래스를 가져오고 메타 데이터를 적용하여 파생 클래스를 설명합니다. 웹 서비스에서 XML이 다형성 플레이에 있음을 나타내는 type
속성을 포함하는 경우> JSON 파서는 $type
속성을 추가 -
는이 XML이 있음을 아는 것이 중요합니다, 다음 코드를 이해합니다.
기본 형식에 적용되는 실제 메타 데이터는 XML의 형식 이름과 파생 된 형식의 생성자입니다.
메타 데이터 등록 및 클래스 장식 :
export interface IJsonPolymorphism {
name: string;
clazz: {new(): any};
}
export function RegisterForPolymorphism(name: string) {
return (target) => {
let metadata = getJsonPolymorphism(target.__proto__);
if (!metadata) {
metadata = [];
}
metadata.push({name: name, clazz: target});
target.__proto__ = Reflect.metadata(jsonPolymorphismMetadataKey, metadata)(target.__proto__);
return target;
};
}
export function getJsonPolymorphism(target: any): IJsonPolymorphism[] {
return Reflect.getMetadata(jsonPolymorphismMetadataKey, target);
}
사용법 : 클래스 데코레이터에 전달 웹에서 XML 응답의 type
속성의 값입니다 있습니다
// The base class
export class PropertyBase { /*...*/ }
// The derived classes
//
@RegisterForPolymorphism("b:PicklistProperty")
export class PicklistProperty extends PropertyBase { /*...*/ }
@RegisterForPolymorphism("b:TextProperty")
export class TextProperty extends PropertyBase { /*...*/ }
문자열 서비스. 디시리얼라이저의
코드는 다음처럼 사용한다 :
if (jsonObject["$type"]) {
const polymorphism = getJsonPolymorphism(clazz);
if (polymorphism && polymorphism.filter) {
const subclassDefinition = polymorphism.filter(x => x.name === jsonObject["$type"])[0];
if (subclassDefinition && subclassDefinition.clazz) {
clazz = subclassDefinition.clazz;
}
}
}
는 기본적으로, clazz
가로 JSON 객체를 직렬화 할 수있는 유형의 생성자이며, 우리는 파생 형식의 생성자로 교체합니다.
이 코드는 현재 메타 데이터를 직접 기본 클래스, 전체 계층 구조에만 추가한다는 제한이 있습니다. 그러나 이것은 RegisterForPolymorphism
내부의 코드를 조정하여 쉽게 풀 수 있습니다.
현재 TypeScript 용으로 [비 목적] (https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals)입니다. 당신이 해결하려고하는 실제 문제는 무엇입니까? –
https://frhagn.github.io/Typewriter/를 사용하여 TypeScript에서 클래스를 만드는 방법에 대해 알려주십시오. –
@PaulBullivant 나는 그 도구를 좋아하지만 그가 뭔가 다른 것을 찾고 있다고 생각한다. –