5.2 KiB
5.2 KiB
In [2]:
class Human {
constructor(name, age){
this.name = name;
this.age = age;
}
toJSON(){
return {
type: "Human",
age: this.age,
name: this.name,
}
}
}
class Gnome{
constructor(name, height){
this.name = name;
this.height = height;
}
toJSON(){
return {
type: "Gnome",
name: this.name,
height: this.height,
}
}
}
In [6]:
const persons = [
new Human("Boutros", 89),
new Human("Fares", 12),
new Gnome("Petit Pied", 102),
new Gnome("Grand Gaillard", 135),
]
function serializePersons(persons){
const personObjets = persons.map(person => person.toJSON())
localStorage.setItem("persons.json", JSON.stringify(personObjets));
}
serializePersons(persons)In [7]:
console.log(localStorage.getItem("persons.json"))[{"type":"Human","age":89,"name":"Boutros"},{"type":"Human","age":12,"name":"Fares"},{"type":"Gnome","name":"Petit Pied","height":102},{"type":"Gnome","name":"Grand Gaillard","height":135}]
In [22]:
function deserializeHumanObject(humanObject){
return new Human(humanObject.name, humanObject.age)
}
function deserializeGnomeObject(gnomeObject){
return new Gnome(gnomeObject.name, gnomeObject.height)
}
function deserializePersonObject(person){
if(person.type === "Human"){
return deserializeHumanObject(person);
}
if(person.type === "Gnome"){
return deserializeGnomeObject(person);
}
}
function deserializePersons(){
const personObjects = JSON.parse(localStorage.getItem("persons.json"));
if(!personObjects){
return []; // le cas ou il n'y a rien de sauvegarder dans "persons.json"
}
return personObjects.map(deserializePersonObject)
}In [20]:
deserializePersons()Out [20]:
[]
In [21]:
localStorage.clear() // efface tout du localstorage. Le cas du premier visiteur
deserializePersons()Out [21]:
[]