1

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.

0

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer, but I didn't explain very well. I edit my response to give more detail about my Customer class and the json file.
As of now, you can also implement a custom converter, which may look a little bit nicer. But of course this solution works as well!
0

Seems like the response JSON is already in a good format and you don’t need to do the conversion. I would recommend creating models as they allow for serialization and deserialization when making API calls and binding the response to that model.

1 Comment

Sorry, but I don't understand your answer. Could you be more specific and give me an example please? Thanks in advance :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.