typescript-json-serializer
typescript-json-serializer copied to clipboard
[FEAT]: Remove unrecognized properties during serialization
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
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.
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
I finally merged the 5.1.0 version, hope that's what you need.