Array()上的.to_json无法在Crystal中运行

twh*_*mon 3 arrays json crystal-lang

我有一节课:

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
Run Code Online (Sandbox Code Playgroud)

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

在/usr/local/Cellar/crystal-lang/0.23.1_3/src/json/to_json.cr:66:没有重载匹配'User#to_json'与类型JSON :: Builder重载是: - User#to_json() - Object#to_json(io:IO) - Object#to_json()

  each &.to_json(json)
Run Code Online (Sandbox Code Playgroud)

Array(String)#to_json工作得很好,为什么不Array(User)#to_json呢?

Vit*_*upt 7

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

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":"****"}]
Run Code Online (Sandbox Code Playgroud)