0

I have an Angular project with a model that looks like this:

export class Party {
  name!: string;
  address!: string;
}

export class Bank extends Party {
  bic: string|null = null; 
}

The frontend needs to both read and write collections of such parties (mixed collections of Party and Bank instances) to/from a REST service implemented in Spring Boot. Because the logic (both frontend and backend) is different if a party is a Bank, it is essential that the correct (sub)types are instantiated when deserializing the JSON data, both in the frontend and the backend.

On the backend/Java side there is the exact same class structure:

@JsonTypeInfo(use= JsonTypeInfo.Id.NAME, property = "type")
@JsonSubTypes({
        @JsonSubTypes.Type(value=Party.class, name="party"),
        @JsonSubTypes.Type(value=Bank.class, name="bank")})
public class Party {
    private String name;
    private String address;
}

public class Bank extends Party {
    private String bic;
}

As you see I have already implemented part of the solution by annotating the Java class with @JsonTypeInfo and @JsonSubTypes. This produces JSON payload that looks like this:

{
  "parties": [
    {
      "type": "party",
      "name": "John Smith",
      "address": "Some address",
    },
    {
      "type": "bank",
      "name": "UBS SWITZERLAND AG",
      "address": "Another address",
      "bic": "UBSWCHZHXXX"
    }
  ],
  "apiErrors": []
}

which is consumed in Angular like this:

public getParties() : Observable<Party[]> {
  
  return this.httpClient.get(PARTIES_URL, {headers: AppConfig.HEADERS}).pipe(
    map((response) => {
       return response['parties'];
    })
  );
}

however response['parties'] is just an array of "raw" JavaScript Objects and not Party or Bank instances.

What do I need to do in TypeScript so that

  • the JSON is deserialized into the correct types (Party or Bank instances)
  • the Party or Bank instances are serialized back into JSON that contains the correct type information ?
mpapado
  • 23
  • 4
  • Does this answer your question? [How do I cast a JSON Object to a TypeScript class?](https://stackoverflow.com/questions/22875636/how-do-i-cast-a-json-object-to-a-typescript-class) – douglas rouse Dec 05 '22 at 12:23

0 Answers0