.to_json 上的 Array() 在 Crystal 中不起作用

.to_json on Array() not working in Crystal

我有一个 class:

class User
    property id : Int32?
    property email : String?
    property password : String?

    def to_json : String
        JSON.build do |json|
            json.object do
                json.field "id", self.id
                json.field "email", self.email
                json.field "password", self.password
            end
        end
    end

    # other stuff
end

这适用于任何 user.to_json。但是当我有 Array(User) (users.to_json) 它会在编译时抛出这个错误:

in /usr/local/Cellar/crystal-lang/0.23.1_3/src/json/to_json.cr:66: no overload matches 'User#to_json' with type JSON::Builder Overloads are: - User#to_json() - Object#to_json(io : IO) - Object#to_json()

  each &.to_json(json)

Array(String)#to_json 可以正常工作,为什么 Array(User)#to_json 不行?

Array(User)#to_json 不起作用,因为 User 需要有 to_json(json : JSON::Builder) 方法(而不是 to_json),就像 String has:

require "json"

class User
  property id : Int32?
  property email : String?
  property password : String?

  def to_json(json : JSON::Builder)
    json.object do
      json.field "id", self.id
      json.field "email", self.email
      json.field "password", self.password
    end
  end
end

u = User.new.tap do |u|
  u.id = 1
  u.email = "test@email.com"
  u.password = "****"
end

u.to_json      #=> {"id":1,"email":"test@email.com","password":"****"}
[u, u].to_json #=> [{"id":1,"email":"test@email.com","password":"****"},{"id":1,"email":"test@email.com","password":"****"}]