shakilsiraj / json-object-mapper

A TypeScript library to serialize and deserialize object graph from/to JSON in a fast and non-recursive way
MIT License
58 stars 18 forks source link

Add @JsonIgnore (or similar functionality) #7

Closed doctore closed 7 years ago

doctore commented 7 years ago

Hi

Sometimes it is necessary to include in the model (DTO in this case), several properties that you don't want to serialize and/or deserialize, so it would be nice add this functionality to this library.

Thanks in advance

shakilsiraj commented 7 years ago

Hi there,

It's already supported, you will need to specify access type (READ_ONLY, WRITE_ONLY or BOTH) for the property - default is BOTH. Here are couple of test cases for you:

it("Testing AccessType.READ_ONLY", () => {

    class SimpleClass {
        firstName: string = "John";
        middleName: string = "P";
        lastName: string = "Doe";
        @JsonProperty({ type: String, name: "AKA", access: AccessType.READ_ONLY })
        knownAs: String[] = ["John", "Doe", "JohnDoe", "JohnPDoe"]
    };

    let intance: SimpleClass = new SimpleClass();

    let stringrified: String = ObjectMapper.serialize(intance);
    expect(stringrified).toBe('{"firstName":"John","middleName":"P","lastName":"Doe"}');

});

it("Testing AccessType.WRITE_ONLY", () => {
    class Roster {
        @JsonProperty({access:AccessType.WRITE_ONLY})
        private name: string = undefined;
        private worksOnWeekend: boolean = false;
        private today: Date = new Date();
        public isAvailable(date: Date): boolean {
            if (date.getDay() % 6 == 0 && this.worksOnWeekend == false) {
                return false;
            }
            return true;
        }
        public isAvailableToday(): boolean {
            return this.isAvailable(this.today);
        }
        public getName(): String {
            return this.name;
        }
    }

    var json = {
        'name': 'John Doe',
        'worksOnWeekend': false
    }

    var testInstance: Roster = ObjectMapper.deserialize(Roster, json);
    expect(testInstance.getName()).toBeUndefined();
});
doctore commented 7 years ago

Thanks for your answer.

shakilsiraj commented 7 years ago

No worries.

ghost commented 7 years ago

Hello,

First: thanks a lot for this library :stuck_out_tongue:

I'd like to reopen this issue because I actually could use an AccessType.NEVER for properties that you neither want to serialize or deserialize. I don't see how it's possible with existing options.

Thanks in advance!

marctanguy commented 7 years ago

Hi !

I need exactly the same feature ! 'AccesType.NEVER'

Thanks !

shakilsiraj commented 7 years ago

There is @JsonIgnore in 1.5

ghost commented 7 years ago

I saw that. Thanks a lot :)

Sent from my Bq Aquaris X5 Plus using FastHub