hussain
hussain

Reputation: 7083

how to map json with typescript interface?

i have response from backendthat i am trying to map it to interface but its always throws interface properties undefined like in below case Envelop always coming undefined. Any idea what is implemented wrong here ?

interface.ts

export interface IResult {
    Envelop: Envelope;
}

export interface Envelope {
    $: $;
    Header: string;
    Body: Body;
}
export interface $ {
    "xmlns:soapenv": string;
}

export interface Body {
    "trk:TrackResponse": TrackShipment;
}

main.ts

public after(data: IResult){

        const result = data.Envelop.Body
        const response: any = result;
        return response;
    }

Json data from backend

"soapenv:Envelope": {
     "$": {
         "xmlns:soapenv": "http"
     },
     "soapenv:Header": "",
     "soapenv:Body": {
         "some test Data"
     }
 }

Upvotes: 1

Views: 2184

Answers (1)

Joseph Webber
Joseph Webber

Reputation: 2173

Given your response JSON, your interfaces should look like this

export interface IResult {
    "soapenv:Envelope": Envelope;
}
export interface Envelope {
    $: $;
    "soapenv:Header": string;
    "soapenv:Body": Body;
}
export interface $ {
    "xmlns:soapenv": string;
}
export interface Body {
    "trk:TrackResponse": TrackShipment;
}

Which you would then access like

public after(data: IResult) {
  const result: Body = data["soapenv:Envelope"]["soapenv:Body"];
  return result;
}

Upvotes: 1

Related Questions