JSON:API Serializer for Crystal Lang, see JSON:API Specification at https://jsonapi.org/
Installation
-
Add the dependency to your
shard.yml:dependencies: jsonapi-serializer-cr: github: andersondanilo/jsonapi-serializer-cr
-
Run
shards install
Usage
Define your resource
class MyResource property id : Int32? property name : String property description : String? property other_resource : OtherResource? property dependencies : Array(Dependency) = [] of Dependency property brother_id : Int32? def initialize(@name) end end
Define your serializer
class MyResourceSerializer < JSONApiSerializer::ResourceSerializer(MyResource) identifier id type "my-resource" attribute name attribute description relationship(other_resource) { @other_resource_serializer } relationship(dependencies) { DependencyResourceSerializer.new } relationship_id brother_id, "brother", "brothers" def initialize(@other_resource_serializer : OtherResourceSerializer) super(nil) end end
Start serializing and deserializing
require "jsonapi-serializer-cr" # instantialize serializer (MyResourceSerializer) and entity (MyResource) # ... # serialize json = serializer.serialize(entity) # or deserialize entity = serializer.deserialize(json) # You can set options to the serializer serializer.options = JSONApiSerializer::SerializeOptions.new(change_case: "camelcase") # You can deserialize a object replacing the attributes based on an already constructed object (updating an existing object) entity = serializer.deserialize! json, my_resource # The difference between "deserialize!" and "deserialize" is that "deserialize!" throws JSONApiSerializer::DeserializeException, "deserialize" only return nil
Contributing
- Fork it (https://github.com/your-github-user/jsonapi-serializer-cr/fork)
- Create your feature branch (
git checkout -b feature/my-new-feature) - Commit your changes (
git commit -am 'Add some feature') - Push to the branch (
git push origin feature/my-new-feature) - Create a new Pull Request
Contributors
- Anderson Danilo - creator and maintainer