Search code examples
crystal-lang

Why is include JSON::Serializable needed in this struct in Crystal?


In order to do .to_json on this Struct of Book, the include JSON::Serializable is needed, there are answers for this in other languages, but I thought there should be something about this in Crystal or Crystal lang.

struct Book
    include JSON::Serializable # Needed to parse JSON
    def initialize(
      @Id : Int32,
      @Title : String,
      @Author : String,
      @Desc : String
    )
    end
end

https://crystal-lang.org/api/1.4.1/JSON.html#generating-with-to-json Here is some documentation on this.


Solution

  • The JSON::Serializable module automatically generates methods for JSON serialization when included.

    Including JSON::Serializable will create #to_json and self.from_json methods on the current class, and a constructor which takes a JSON::PullParser. By default, these methods serialize into a json object containing the value of every instance variable, the keys being the instance variable name.