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

[FEAT]: Remove unrecognized properties during serialization

Open shcallaway opened this issue 2 years ago • 2 comments

Description

Hi! First of all, thanks for creating this great library.

I was thinking it would be nice if I JsonSerializer could be configured to throw an error when serializing an object that has unexpected properties, i.e. properties that were not defined on the JsonObject.

@JsonObject()
export class MyClass {
  @JsonProperty({ required: true })
  foo: string;
}

const myClassInstance = new MyClass();
myClassInstance.foo = "foo";

// @ts-ignore
myClassInstance.bar = "bar";

const serializer = new JsonSerializer({ errorCallback: throwError });

// I would like for this to throw some kind of error, e.g. "SerializationError: object contains unexpected properties"
serializer.serialize(myClassInstance);

Thoughts?

Proposed solution

A new configuration option on JsonSerializer that causes JsonSerializer.serialize to throw an error (or at least invoke the errorCallback) when it encounters a property that was not included on the JsonObject.

Some ideas for what this config could be called: disallowUnexpectedProperties, strictSerialization, errorOnUnexpectedProperty

shcallaway avatar Oct 02 '22 17:10 shcallaway

Hi, non JsonProperty are removed during the serialization. It can't throw an error because your class could contain properties that you do not want to serialize.

The only thing I can do is to provide a new Decorator for this kind of property, for example: @IgnoredProperty. But it means that it will create a breaking change because the code will throw now if the property is not ignored.

GillianPerard avatar Oct 04 '22 12:10 GillianPerard

Hi, I found another solution.

I mimic the nullishPolicy system by creating a new option for JsonSerializer where you could manage the policy for additional properties (allow, disallow, remove; to avoid breaking changes I set the default value to remove.

Before I merge, tell me if you want to test it! https://github.com/GillianPerard/typescript-json-serializer/pull/192

GillianPerard avatar Oct 25 '22 16:10 GillianPerard

I finally merged the 5.1.0 version, hope that's what you need.

GillianPerard avatar Nov 01 '22 08:11 GillianPerard