0

I have a class, for example, let's say a Car with the below structure.

@Serializable()
export default class Car {
  @JsonProperty({
    name: 'id'
  })
  private id!: string;

  @JsonProperty({
    name: 'name'
  })
  private name!: string;

  @JsonProperty({
    name: 'carOwner'
  })
  private carOwner!: Owner;
}

Further I have the Owner class.

@Serializable()
export default class Owner{
  @JsonProperty({
    name: 'id'
  })
  private id!: string;

  @JsonProperty({
    name: 'name'
  })
  private name!: string;

  @JsonProperty({
    name: 'address'
  })
  private address!: string;
}

I have an incoming JSON Object with below structure, let's call it newCar

{
  "id": "test-id",
  "name": "test-car",
  "carOwner": {
    "id": "owner-id",
    "name": "owner-name",
    "address": "owner-address",
    "gender": "owner-gender",
    "age": "owner-age",
  }
}

What I want to do is, deserialize the newCar JSON to the Car class. That is when I deserialize newJson I should get the below object, where gender and age are filtered out.

{
  "id": "test-id",
  "name": "test-car",
  "carOwner": {
    "id": "owner-id",
    "name": "owner-name",
    "address": "owner-address"
  }
}

But right now what I am getting is the original newJson. It seems that the library (typescript-json-serializer) which I am using does not deserialize nested objects, here which is owner.

Any input will be appreciated.

Here is the link to the package typescript-json-serializer

6
  • 1
    Maybe this helps. github.com/GillianPerard/typescript-json-serializer/issues/82 Is Owner marked as Serializable? Commented Oct 21, 2021 at 12:44
  • 1
    @tiriana Yes, Owner is marked Serializable. Apologies that I didn't mention it in code. I'll edit. Commented Oct 21, 2021 at 12:47
  • No worries. And when you deserialize - do you pass the Car class as second argument? typescriptJsonSerializer.deserialize(newCar, Car); Commented Oct 21, 2021 at 12:55
  • 1
    @tiriana I found the solution for it. Apparently I missed to pass the type Owner inside the JsonProperty() for owner in Car class. Commented Oct 21, 2021 at 13:06
  • Well, glad I "helped" :) Commented Oct 21, 2021 at 13:15

1 Answer 1

1

Found the solution for it. Apparently I missed to add one parameter in JsonProperty(). In the Car class, for carOwner object, I had to pass type of owner.

@JsonProperty({
    name: 'carOwner',
    type: Owner,
})

The above solved the issue I was facing.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.