我有一堂课:
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:中,没有与JSON::Builder重载类型“User#to_json”匹配的重载是:- User#to_json() - Object#to_json(io : IO) - Object#to_json() 每个&.to_json(json)
Array(String)#to_json工作得很好,那么为什么Array(User)#to_json不能
发布于 2017-10-23 12:45:16
Array(User)#to_json不能工作,因为User需要有to_json(json : JSON::Builder)方法(而不是to_json),就像字符串有一样
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":"****"}]https://stackoverflow.com/questions/46889601
复制相似问题