GillianPerard/typescript-json-serializer

[FEAT]: Access a parent value of the JSON to serialize

KyDenZ opened this issue · 6 comments

Description

I am trying your librairie. I am a fan of the possibilities it offers. Thank you !

I want to retrieve a value of my object to serialize from a child class :

{
  "type": "layout",
  "version": "1.0.0",
  "value": {
    "name": "test"
  }
}
@Serializable()
export class Root {
  @JsonProperty({
    name: 'version',
    type: String,
  })
  version!: string;

  @JsonProperty({
    name: 'value',
    type: Value,
  })
  value!: Value;
}
@Serializable()
export class Value {
  @JsonProperty({
    name: 'name',
    type: String,
  })
  name!: string;

  @JsonProperty({
    name: '../type', // type of the parent element
    type: String,
  })
  type!: string;
}

Is there a way to access in my class value the type value of the parent object?

Thank you !

Proposed solution

In the source code, I didn't find a solution.
We could add in the functions beforeDeserialize / afterDeserialize... a parameter containing the object to serialize

Hi, thank you for using my lib :).

You're right, if I can pass the parent instance to the before/after methods you'll can set/unset the data you want.
Let me check that ASAP.

Just a thing you can simplify the code you wrote by doing:

@Serializable()
export class Root {
  @JsonProperty() version!: string;
  @JsonProperty() value!: Value;
}

@Serializable()
export class Value {
  @JsonProperty() name!: string;
  @JsonProperty({beforeDeserialize: ...}) type!: string;
}

Thank you very much!

Just for your information, I just release the new major version and it comes with multiple breaking changes.
I'll look at your issue now :).

So I send again the new version of your code according to the version 4.

@JsonObject()
export class Root {
  @JsonProperty() version!: string;
  @JsonProperty() value!: Value;
}

@JsonObject()
export class Value {
  @JsonProperty() name!: string;
  @JsonProperty({beforeDeserialize: ...}) type!: string;
}

Thanks for your responsiveness! Let me know if I can help 🙂

Hi, I apologize but I can't provide the parent instance to the before/after functions because I can't assure that the instance is complete, you could retrieve only a part of this instance according to the order of properties.

I've no solution for you, so I close this issue...