Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- export class Serializable {
- public static createInstanceFromJson<T>(objType: { new(): T; }, json: any) {
- const newObj = new objType();
- const relationships = objType["relationships"] || {};
- for (const prop in json) {
- if (json.hasOwnProperty(prop)) {
- if (newObj[prop] == null) {
- if (relationships[prop] == null) {
- newObj[prop] = json[prop];
- }
- else {
- if (json[prop] instanceof Array) {
- newObj[prop] = [];//init array
- for (let i = 0; i < json[prop].length; i++) {
- let val = Serializable.createInstanceFromJson(relationships[prop], json[prop][i]);
- newObj[prop].push(val);
- }
- } else {
- newObj[prop] = Serializable.createInstanceFromJson(relationships[prop], json[prop]);
- }
- }
- }
- else {
- console.warn(`Property ${prop} not set because it already existed on the object.`);
- }
- }
- }
- return newObj;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement