Reputation: 53
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.
I want for the app to be able to save and load the exams as JSON. My current solution is:
constructor(private http:Http) {
this.http.get('Exam.json')
.map((response) => {
return response.json();
}).subscribe(data => {
this.exam = <Exam>data;
//console.log(typeof(<Exam>data));
console.log(this.exam);
this.refreshMarksMethods(this.exam);
});
}
The first issue is that the JSON is deserialized as a plain object. I attempted to use serializer.ts (https://www.npmjs.com/package/serializer.ts) and class-transformer(https://github.com/pleerock/class-transformer) 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.
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).
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).
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.
Upvotes: 3
Views: 3765
Reputation: 21985
I made a little package called json-dry. It supports (circular) references and also class instances.
You have to define 2 class methods (toDry
on the prototype and unDry
as a static method), register the class, and off you go.
I've been using it for years and it's able to serialize very large collections, too.
Upvotes: 1