json-object-mapper icon indicating copy to clipboard operation
json-object-mapper copied to clipboard

Serialize & Deserialize when the class attribute is null

Open tomas-ortega opened this issue 8 years ago • 4 comments

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:

tomas-ortega avatar Aug 21 '17 14:08 tomas-ortega

I have the same problem using the version 1.5.1 (that solves the issue https://github.com/shakilsiraj/json-object-mapper/issues/12)

doctore avatar Nov 02 '17 11:11 doctore

Same here, it doesn't seem to be working properly when the object has an attribute with null value

jrmsamson avatar Nov 03 '17 10:11 jrmsamson

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 ?

ghost avatar Nov 03 '17 14:11 ghost

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.

tommiv avatar Dec 19 '18 16:12 tommiv