appvision-gmbh / json2typescript

Map JSON to a TypeScript class with secure type checking!
https://www.npmjs.com/package/json2typescript
MIT License
278 stars 55 forks source link

Null object while serializing objects #127

Closed sagunpandey closed 4 years ago

sagunpandey commented 4 years ago

I have a deeply nested object structure. Here's a minified version of that object

@JsonObject()
export class Settings {
  @JsonProperty('Options', Options, true) options: Options = null;
}

@JsonObject()
export class Options {
  @JsonProperty('FilterOptions', FilterOptions, true) filterOptions: FilterOptions = null;
  @JsonProperty('TemplateID', Number, true) templateId: number = null;
}

@JsonObject()
export class FilterOptions {
  @JsonProperty('ExcludeDocuments', Boolean, true) excludeDocuments: boolean = null;
}

I am creating the instance of that object in the following way:

const settings= new Settings();
settings.options= {
  templateId: formValue.template,
  filterOptions: {
    excludeDocuments: formValue.excludeDocuments
  } as FilterOptions
} as Options;

While serializing this object I am getting an empty object for options. In my actual use-case, I am getting empty objects for all inner properties that are objects.

I tried to debug out the reason and found that the prototypes __jsonconvert__mapping__ and __jsonconvert__class_identifier__ were missing. If I am not wrong these are the mapping options required for serializing and every object in the structure is supposed to have them. I noticed that json2typescript library adds these properties while deserializing but are missing if I am hand creating already deserialized objects.

How can we adapt or convert an object which is already in deserialized form but with missing json mapping options into something that json2typescript can serialize?

andreas-aeschlimann commented 4 years ago

Have you tried passing a class identifier in the decorator, for example @JsonObject("Settings")?

Anyway, I think this will not work because you don't actually have class instances here.

For example, you create

filterOptions: {
    excludeDocuments: formValue.excludeDocuments
  } as FilterOptions

While this compiles, the property filterOptions is not really an instance of FilterOptions. I think right now this is mandatory.

By the way, I think a PR (https://github.com/AppVision-GmbH/json2typescript/pull/126) will resolve your issue, because it will allow non-instances to be serialized as well.

sagunpandey commented 4 years ago

@andreas-aeschlimann Thank you so much for your input. Do you know this is coming to the release? We have a two years old huge application and this is breaking everything.

Thank you again.

andreas-aeschlimann commented 4 years ago

I will close this issue in favor of the PR #126.