1

In my Angular2-App I´m receiving a JSON-Response via http-Request that kind of looks like that:

{
  "documents": [
    {
      "title": "Example-Doc 1",
      "versions": [
        {
          "fileSize": 15360
        },
        {
          "fileSize": 2048
        }
      ]
    },
    {
      "title": "Example-Doc 2",
      "versions": [
        {
          "fileSize": 15360
        },
        {
          "fileSize": 2048
        }
      ]
    }
  ],
  "meta": {
    "total": [2]
  }
}

Now i wonder how to map this structure into my TypeScript-Classes, i checked different approaches, but it never worked. I actually need the constructor of the Version class to be called.

export class Document {
  title: string;        // Titel des Dokuments
  versions: Version[]; 
}

1 Answer 1

1

If you have complex classes that need to be serialized and deserialized, I suggest that you implement static methods to your classes like fromJson and toJson - however without knowing your classes the rest of the answer will be kind of a guess-work:

Assuming you have a fromJson in place, then you can map your data like the following:

const myDocuments: Document[] = myJson.documents.map(Document.fromJson);

And the fromJson-method could look like this:

class Document {
    constructor(public title: string, public versions: Version[]) 

    public static fromJson(json: any): Document {
        return new Document(
            json.title,
            json.versions.map(Version.fromJson)
        );
    }
}

class Version {
    constructor(public fileSize: number) {}

    public static fromJson(json: any): Version {
        return new Version(json.fileSize);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.