我有一个班级:
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
)时,它会在编译时抛出此错误:
在/usr/local/Cellar/crystal-lang/0.23.1_3/src/json/to_json.cr:66:否 重载匹配'User#to_json'与类型JSON :: Builder重载是: - 用户#to_json() - Object#to_json(io:IO) - Object#to_json()
each &.to_json(json)
Array(String)#to_json
工作正常,为什么不Array(User)#to_json
?
答案 0 :(得分:7)
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":"****"}]