title: Serialize and deserialize JSON with Angular 2
body: <p>I want to use Angular 2 to make a browser app where you can make and share mock exams. I have a Exam class instance containing ExamSection class instances which contain ExamQuestion class instances etc. </p>
  
  <p>I want for the app to be able to save and load the exams as JSON. My current solution is:</p>
  
  <pre><code>constructor(private http:Http) {
      this.http.get('Exam.json')
              .map((response) =&gt; {
                return response.json();
  
              }).subscribe(data =&gt; {
                this.exam = &lt;Exam&gt;data;
                //console.log(typeof(&lt;Exam&gt;data));
                console.log(this.exam);
                this.refreshMarksMethods(this.exam);
              });
  
  }
  </code></pre>
  
  <p>The first issue is that the JSON is deserialized as a plain object. I attempted to use serializer.ts (<a href="https://www.npmjs.com/package/serializer.ts" rel="nofollow noreferrer">https://www.npmjs.com/package/serializer.ts</a>) and class-transformer(<a href="https://github.com/pleerock/class-transformer" rel="nofollow noreferrer">https://github.com/pleerock/class-transformer</a>) to do serialization and deserialization for the TypeScript classes that Angular works with but I keep getting errors relating to missing modules. The modules that are missing are not referenced in the examples for those libraries, as far as I can work out, so I don't know where they belong.</p>
  
  <p>A trick I tried to work around the issue was to cast the plain objects into the needed Typescript type but this doesn't work (the object type does not change). Because the objects are plain objects, I loose the methods and also properties like length (for arrays).</p>
  
  <p>Can someone please explain to me how I'd go about converting TypeScript objects to and from JSON within a Angular app, including how and where the required libraries go? Sometimes putting the module in the "node_modules" folder works, and sometimes it belongs somewhere in the "src" folder (I have to work this out with trial-and-error usually).</p>
  
  <p>Edit: I got a hacky solution working where the objects described in the JSON have a "deserialize" method which is used to recursively reconstruct the class instances. I'm hoping someone can explain how to use a different solution because I doubt my current solution will work for large projects.</p>