【问题标题】:.to_json on Array() not working in CrystalArray() 上的 .to_json 在 Crystal 中不起作用
【发布时间】:2017-10-23 12:37:32
【问题描述】:

我有一堂课:

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() - 对象#to_json(io : IO) - 对象#to_json()

  each &.to_json(json)

Array(String)#to_json 工作正常,那为什么Array(User)#to_json 不能呢?

【问题讨论】:

    标签: arrays json crystal-lang


    【解决方案1】:

    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":"****"}]
    

    【讨论】:

    • 谢谢。这也解决了其他问题。
    • 也看看JSON.mapping,它可能会清理你的代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-07
    • 2022-07-20
    • 1970-01-01
    • 1970-01-01
    • 2017-01-13
    相关资源
    最近更新 更多