1.2.1 • Published 1 month ago

@mdcc/at-json v1.2.1

Weekly downloads
-
License
MIT
Repository
github
Last release
1 month ago

at-json

Build Status

A declarative mapper to and from JSON.

Installation

npm install @mdcc/at-json

Usage

import { JsonClass, JsonProperty, JsonArray, JsonComplexProperty, JsonMapper } from '@mdcc/at-json';

@JsonClass()
class Payload {
    // maps a "name" property to the field
    @JsonProperty() name: string;
    // maps a "SN" property to the field "surname"
    @JsonProperty('SN') surname: string;
    // maps an array of numbers named "numbers" to the field
    @JsonArray() numbers: number[];
    // maps a complex type recursively
    @JsonComplexProperty(SubClass) sub: SubClass;
}

@JsonClass()
class SubClass {
    // other mappings
    @JsonProperty() x: number;
    @JsonProperty() y: number;

    get norm(): double {
        return Math.sqrt(this.x * this.x + this.y * this.y);
    }
}

// ...
const payloadObject = {
    name: 'name',
    SN: 'surname',
    numbers: [1, 2, 3],
    sub: {
        x: 1,
        y: 2,
    },
};

// create a mapper instance
const mapper = new JsonMapper();

// you can deserialize objects, or JSON strings too!
const mapped = mapper.deserialize(Payload, payloadObject);
const mappedFromString = mapper.deserialize(Payload, JSON.stringify(payloadObject));

// mapped is a Payload instance
expect(mapped instanceof Payload).toBe(true);

// fields are deserialized accordingly to the names specified in decorators
expect(mapped.name).toBe('name');
expect(mapped.surname).toBe('surname');

// mapped.sub is a SubClass instance
expect(mapped.sub instanceof SubClass).toBe(true);
expect(mapped.sub.norm).toBe(Math.sqrt(5));

Documentation

Documentation can be found here.

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

License

MIT

1.2.0

1 month ago

1.2.0-beta.0

1 month ago

1.2.1

1 month ago

1.1.1

7 months ago

1.1.0

7 months ago

1.0.2

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago

1.0.0-3

2 years ago