Search code examples
jsonangulartypescriptfrontendangular4-httpclient

Angular 4 - Typescript: json2typescript json key mapper


Sorry but I didn't explain it very well. I edit my question again:

I have an angular 4 application and I use json2typescript to convert from json to object and vice versa but I have a problem because I have a class structure and the response json from an external api has another structure. Example:

Customer {
  @JsonProperty('idCardNumber', String)
  idCardNumber: string = undefined;
  @JsonProperty('rolInfo.name',String) 
  name: string = undefined;
  @JsonProperty('rolInfo.surname',String) 
  surname: string = undefined;  
}

External Json API Reponse:

 {
   "idCardNumber": "08989765F",
   "rolInfo": {
      "name": "John"
      "surname: "Smith"
   }
 }

So, I would like to map from the json above to my Customer object and not to change my structure. I tried to put 'rolInfo.name' into the JsonProperty, but that doesn't work.


Solution

  • Change your Customer class to something like below

    Customer {
      @JsonProperty('idCardNumber', String)
      idCardNumber: string = undefined;
    
      @JsonProperty('rolInfo', Any) 
      rolInfo: any = {}; // if you set this to undefined, handle it in getter/setter
    
      get name(): string {
          return this.rolInfo['name'];
      }
    
      set name(value: string) {
          this.rolInfo['name'] = value;
      }
    
      get surname(): string {
         return this.rolInfo['surname'];
      }
    
      set surname(value: string) {
          this.rolInfo['surname'] = value;
      }
    }
    

    That should do it