Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Deseriazer overwrites value after object instantiation via its constructor #39

Open
mkotsollaris opened this issue Mar 30, 2018 · 1 comment

Comments

@mkotsollaris
Copy link

mkotsollaris commented Mar 30, 2018

I am trying to deserialize my result of a specific type MyType. For some

const myJson= <MyType><any>resultJson; //resultJson comes through the server with a valid value
myVal = deserialize(MyTypeA, JSON.parse(myJson)); //myVal.a='a' myVal.b='b' and myVal.id=1
myType = new MyType(myVal.a, myVal.b);

MyTypeA has the following structure:

`let i = 0;`
export class MyType{
     
    readonly id: number;
    @JsonProperty('a')
    a: string;

    @JsonProperty('b')
    b: string;

    constructor(a?: string, b?: string) {
        this.a= a;
        this.b= b;
       this.id = i++;
    }
}

However, when I try to instantiate my object my constructor is being called and thereafter the deserializer (via index.js) overwrites my non-annotated readonly attribute from 1 to undefined. This is through the deserialize function.

Any idea why this function overwrites my already-existing attribute?

@tsiegleauq
Copy link

I face the same issue.

To make this a little bit more clear: The following class shall be given

export class MedaFile {
  id: number; //part of JSON
  title: string; //part of JSON
  collection: string //not a part of JSON

  constructor(id?: number, title?: string) {
    this.id = id;
    this.title = title;
    this.collection = 'mediafiles/mediafile';
  }
}

With the following json (response)

{
    id: 1,
    title: "logo-example.png"
}

Now, when create a MediaFile using "new":
const myMediaFile = new MediaFile(response.id, response.title)

the property myMediaFile.collection will be mediafiles/mediafile

in contrast, when we use deserialize like following:
const myMediaFile(MediaFile, response)

the property myMediaFile.collection will be undefined

The funny part: deserialize actually calls the constructor. When you put a console.log(this.collection) in the constructor right after it was set, it works fine but gets overwritten to undefined immediately.

This is a huge deal breaker for this library.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants