2017-05-16 143 views
1

這是我的模型如何序列續集導致成JSON

class Client < Sequel::Model(:clients) 
end 

當我執行

Client.first.to_json 

我得到

"\"#<Client:0x2594b824>\"" 

但是,當我執行

DB[:clients].first.to_json 

我得到正確?

{id: 1, name: "Someone" ... } 

我在做什麼錯了......我用Client.dataset.first.json具有相同的結果也試過。

另外我使用的是MS Access DB,但我不認爲這很重要。

+0

你有這個地方:'Sequel :: Model.plugin:json_serializer'。如果是這樣,什麼是'Client.first.class'? – Kris

+0

好的,我剛剛添加了它,它馬上就起作用了,非常感謝! – Mackaber

+0

我想'Client.first.to_h.to_json'。模型返回該類的一個實例,因此您需要將結果轉換爲散列。 –

回答

0

json庫(Ruby的標準庫的一部分),和其他寶石如的ActiveSupport,具有to_json方法猴子補丁的對象可能是怎樣獲取調用,而不是由Sequel提供的具體to_json方法,該方法知道如何將Sequel::Model實例轉換爲JSON。這是猜測我會感到驚訝的是,JSON庫猴子補丁什麼比其他StringArrayHash

當使用DB[:clients].first,你可能得到一個Hash具有to_json方法,其中作爲Client.first返回一個模型實例不是由json庫提供的通用to_json方法處理的。

嘗試註冊續集JSON插件,這應該優先於猴子修補to_json方法:

Sequel::Model.plugin :json_serializer 

順便說一句,這是爲什麼猴子打補丁往往是一個壞主意,尤其是猴子修補一個很好的指標在庫/寶石命名空間之外的類。

1

您需要使用to_hash

require 'json' 
require 'sequel' 

DB = Sequel.sqlite 
DB.create_table :items do 
    primary_key :id 
    String :name 
    Float :price 
end 
items = DB[:items] 
items.insert(:name => 'abc', :price => rand * 100) 

class Item < Sequel::Model(:items) 
end 

Item.first 
    .to_hash # => {:id=>1, :name=>"abc", :price=>51.47074347440235} 
    .to_json # => "{\"id\":1,\"name\":\"abc\",\"price\":51.47074347440235}"