json-object-mapper
json-object-mapper copied to clipboard
Serialize & Deserialize when the class attribute is null
When you have a class with a null vale in some attribute, custom property name in serialization and deserialization processs not work, and json property name is ignored.
Examples are in TypeScript Syntax
Ex. User Domain Class export class User {
@JsonProperty({name: "id"})
public _id: number;
@JsonProperty({name: "name"})
public _name: string;
@JsonIgnore()
public _password: string;
public constructor() {
this._id = null;
this._name = "Test User Name";
this._password = "gsa@aglaX!";
}
}
Ex. Serialization let userInstance: User; userInstance = ObjectMapper.serialize(singleTestDTO);
User instance: {"_id": null, "name": "Test User Name"}
If don't explicitly initialize _id to null, works, or if initialize to undefined, but no with null value...
It would be wonderful it worked with null values
Congratulations on working with module! :+1:
I have the same problem using the version 1.5.1 (that solves the issue https://github.com/shakilsiraj/json-object-mapper/issues/12)
Same here, it doesn't seem to be working properly when the object has an attribute with null value
Correct me if I'm wrong, but, in the given example, id is of type number. And assigning null to a basic type in Typescript shouldn't be allowed at all (cf. this link for more info). Try using Number instead of number, String instead of string, and Boolean instead of boolean ?
Try using Number instead of number, String instead of string, and Boolean instead of boolean ?
This won't work. Neither as public field: String | null = null; or public field?: String = null;.
By the way, nullable fields behave strange, for example, ObjectMapper.serialize ignores AccessMethod.READ_ONLY in case the field is set to null. For instance:
import { JsonProperty, AccessType } from 'json-object-mapper';
export class HeadSlot {
@JsonProperty({name: 'slot_id'})
public slotID: number = 0;
@JsonProperty({name: 'game_id'})
public gameID: number = undefined;
@JsonProperty({name: 'title', access: AccessType.READ_ONLY})
public title?: String = null;
}
console.log(ObjectMapper.serialize([new HeadSlot()]));
//
// [{"slot_id":1,"title":null}]
It ignored properly in case the real string is assigned to title.