typescript-json-serializer
typescript-json-serializer copied to clipboard
[BUG]: Lib does not serialize correctly on optional (required = false) Array properties which can be undefined.
Version
4.0.1
Description
I am using "typescript-json-serializer": "4.3.0" and I want to serialize a set of nested classes. It seems that the lib does not like 'required: false' Array properties that can be undefined - if used lib doesn't work.
Actual Output
{"classB":[{"classC":{"myAttribute":true}}]}
Correct Output
{"classB":[{"classC":{"my_attribute":true}}]}
I.e. ClassC property 'myAttribute' should be 'my_attribute' as specified in decorator 'name' option.
Error
No Exception thrown
Reproduction
import { JsonObject, JsonProperty, JsonSerializer } from 'typescript-json-serializer';
export type Optional<T> = T | undefined;
@JsonObject()
export class ClassC {
@JsonProperty({ required: false, name: 'my_attribute' })
public myAttribute: Optional<boolean>;
constructor(myAttribute?: boolean) {
this.myAttribute = myAttribute;
}
}
@JsonObject()
export class ClassB {
@JsonProperty({ required: true })
public classC: ClassC;
constructor(classC: ClassC) {
this.classC = classC;
}
}
@JsonObject()
export class ClassA {
@JsonProperty({ required: false, type: ClassB })
public classB: Array<ClassB> | undefined;
constructor(classB?: Array<ClassB>) {
this.classB = classB;
}
}
describe('serialize nested classs', () => {
it('serialize and honor custom property name', () => {
const mapper = new JsonSerializer();
const instanceC = new ClassC(true);
const instanceB: ClassB = new ClassB(instanceC);
const arr: Array<ClassB> = new Array(instanceB);
const instanceA: ClassA = new ClassA(arr);
const data = mapper.serialize(instanceA);
console.log(JSON.stringify(data));
expect(true).toEqual(true);
});
});
On which OS the bug appears?
macOS 11.6.8
What is your project type?
NodeJS
On which build mode the bug appears?
Development
Anything else?
No response
It also looks like 'required' in ClassC is also not honoured. Unless I am using the lib wrongly?
Hi thank you for using my lib.
The problem is that typescript loose the type if the property could be undefined.
I'm working on a solution.
Problem is now fixed in the new 5.0.0 version!
For array/map/set/dictionary that could be also undefined
, you must specify in the JsonProperty
decorator the new param dataStructure
equals to one of the listed elements above.