Website-Suche

TypeScript-Deserialisierung beim Axios-GET-Anfrage-Antwortobjekt


Ich habe die folgende axios GET-Anfrage:

export function getCurrentCart() {
    return axios.get(Constants.ENDPOINT_MENU_TIMESLOTS, getConfig())
        .then(res => {
            let data = (res as AxiosResponse).data;
            if (data != null) {
                // parsing logic to singleton CartStore instance here
                ...
            } else {
                console.error("data is null");
            }
        });
}

welches eine ts CartStore-Klasse abruft:

export class CartStore {
    id: number;
    temporaryTotal: number;
    status: string = "SHOPPING";
    statusLockTime?: any;
    updatedAt?: string;
    createdAt?: string;
    coupon?: Coupon;

    readonly items = observable.shallowArray<CartItem>([]);  // this is a mobx observable

    @computed get hasItem(): boolean {
        return this.items.length > 0;
    }

    @action clear() {
        this.items.clear();
    }
}

wobei Coupon und CartItem die anderen Modellklassen sind.

Hier ist die Beispiel-JSON-Antwort:

{
  "createdAt": "2017-02-16T20:37:13",
  "updatedAt": "2017-02-22T22:48:50",
  "id": 1,
  "status": "SHOPPING",
  "statusLockTime": null,
  "temporaryTotal": 0,
  "items": [
    ... array of some other json object
  ],
  "coupon": {
    ... json object
  }
}

Welche Deserializer-Bibliothek(en) empfiehlt ihr? Eine andere Frage ist: Wie macht man das auf die typischerweise TypeScript-Art, ohne eine Bibliothek zu verwenden?

Verwandte Artikel