json-typescript-mapper icon indicating copy to clipboard operation
json-typescript-mapper copied to clipboard

Deseriazer overwrites value after object instantiation via its constructor

Open mkotsollaris opened this issue 6 years ago • 1 comments

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?

mkotsollaris avatar Mar 30 '18 00:03 mkotsollaris

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.

tsiegleauq avatar Jul 18 '18 09:07 tsiegleauq