首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >阵列上的.to_json ()不能在晶体中工作

阵列上的.to_json ()不能在晶体中工作
EN

Stack Overflow用户
提问于 2017-10-23 12:37:32
回答 1查看 474关注 0票数 3

我有一堂课:

代码语言:javascript
复制
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不能

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-10-23 12:45:16

Array(User)#to_json不能工作,因为User需要有to_json(json : JSON::Builder)方法(而不是to_json),就像字符串有一样

代码语言:javascript
复制
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":"****"}]
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46889601

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档