0

I am developing an Angular4 project and using ta-json for serializing models.

Backend Api are responding something like this :

   {
      "id":1,
      "teams":[
         {
            "id":1,
            "name":"TeamName",
            "members":[
               {
                  "id":1000,
                  "team_id":1
               },
               {
                  "id":1001,
                  "team_id":1
               }
            ]
         }
      ]
   }

team.ts

import {JsonObject, JsonProperty, JsonType} from "ta-json";
import {Player} from './player';

@JsonObject()
export class Team {
    @JsonProperty()
    id: number;

    @JsonProperty()
    @JsonType(Player)
    players: Player[];
}

player.ts

import {JsonObject, JsonProperty, JsonType} from "ta-json";

@JsonObject()
export class Player {
    @JsonProperty()
    id: number;

    @JsonProperty()
    // @JsonType(Team)
    team: Team;
}

I want to convert team_id (presents in api response) to Team object by it's id.

Any help would be appreciated.

Thanks

Rassoul
  • 174
  • 16

1 Answers1

0

You could perhaps take a look at the @BeforeDeserialized() decorate (please refer to this link for more details)

So your Player class would look like this

@JsonObject()
export class Player {
    @JsonProperty()
    id: number;

    @JsonProperty()
    team_id: number;

    @BeforeDeserialized()
    public createTeam(): Team {
        return new Team(this.team_id);
    }
}

Also add the constructor in your Team class so that it can take in team ID as a parameter to instantiate the Team object. Above code not tested or anything as I'm just throwing in some ideas.

As for other possible solutions, please refer to these SO posts, which might be helpful to you as well.

How do I initialize a TypeScript object with a JSON object

JSON to TypeScript class instance?

woodykiddy
  • 6,074
  • 16
  • 59
  • 100
  • How Team class can initialize its new instance just with id ? – Rassoul Dec 18 '17 at 06:12
  • @sr_hosseini use constructor so that id can be passed in? LIke `public team(id) {//...}` – woodykiddy Dec 18 '17 at 08:49
  • I see, Imagine that Team has another property like "name", so we need real source of team object by its id. I need an entity-manager that manages resources and if an object already fetched from api return it. ```@BeforeDeserialized() public createTeam(): Team { this.team = EntityManager.getResource(Team, this.team_id); }``` – Rassoul Dec 18 '17 at 15:39
  • @sr_hosseini if you felt like the answer was helpful, it'd be appreciated if you could vote or rate the answer. thanks. – woodykiddy Dec 21 '17 at 03:22