Search code examples
jsonangularsession-storage

How to get object array from session stored with json.stringify?


I have a class:

export class CartItem {  
  productname!: string;
  quantity!: number;
}

I store an array of this in session as:

cartItems: Array<CartItem> = [];
...
...
sessionStorage.setItem("CurrentCart", JSON.stringify(this.cartItems));

When retrieving this, I tried:

this.cartItems = JSON.parse(sessionStorage.getItem("CurrentCart") || '') as Array<CartItem>;

But this returns:

Cart Items [object Object],[object Object],[object Object],[object Object]

and not the array with values.

From what I see in some examples Angular convert json to array of object, seems I need to map the array back or write a custom transformer https://medium.com/typescript-center/casting-json-objects-to-typescript-classes-a-deep-dive-835b8f8988bf

Is that the only way? Seems inefficient and cumbersome for bigger classes.


Solution

  • JSON.parse will not convert some arbitrary json to the CartItem class. It will simply convert a json string to json primitives (string, boolean, null, array, object).

    You would need to implement some custom encoding/decoding. Example:

    class CartItem {
      constructor(public productName: string, public quantity: number){}
      toJson(): any {
        return {productName: this.productName, quantity: this.quantity}
      }
      toString(): string{
        return `CartItem{${this.productName}:${this.quantity}}`
      }
      static fromJson(obj: any): CartItem {
        return new CartItem(obj.productName, obj.quantity)
      }
      static fromJsonList(obj: any): CartItem[] {
        return obj.map(item => CartItem.fromJson(item))
      }
    }
    
    class Cart {
      private cartItems: CartItem[] = []
      private static readonly STORE_KEY = "CurrentCart"
      function save(){
        const storedJson = JSON.stringify(this.cartItems.map(item => item.toJson()))
        sessionStorage.setItem(Cart.STORE_KEY, storedJson);
      }
      function load(){
        const storedJson = sessionStorage.getItem(Cart.STORE_KEY) || '[]'
        this.cartItems = CartItem.fromJsonList(JSON.parse(storedJson));
      }
    }