2017-04-03 225 views
0

我找到反向而不是爲嵌套的方式結構,以JSON轉換嵌套的結構以JSON

假設的答案,我有這種紅寶石結構

Attributes = Struct.new :name, :preferredLanguage, :telephoneNumber, :timeZone 
User = Struct.new :email, :service, :preferredLanguage, :attributes 

我創建屬性

的結構
attributes = Attributes.new "Pedro", "es", "5555555", "Madrid" 
# => #<struct Attributes name="Pedro", preferredLanguage="es", telephoneNumber="5555555", timeZone="Madrid"> 
attributes.to_h.to_json 
# => "{\"name\":\"Pedro\",\"preferredLanguage\":\"es\",\"telephoneNumber\":\"5555555\",\"timeZone\":\"Madrid\"}" 
Oj.dump attributes 
# => "{\"^u\":[\"Attributes\",\"Pedro\",\"es\",\"5555555\",\"Madrid\"]}" 
Oj.dump attributes, mode: :compat 
# => "\"#<struct Attributes name=\\\"Pedro\\\", preferredLanguage=\\\"es\\\", telephoneNumber=\\\"5555555\\\", timeZone=\\\"Madrid\\\">\"" 

因此,它運作良好,除了當我使用寶石Oj,我不能刪除對象的名稱,並得到相同的to_h.to_json方法

但問題是當我使用嵌套的結構像用戶

user = User.new "[email protected]", "coolService", "es", attributes 
# => #<struct User email="[email protected]", service="coolService", preferredLanguage="es", attributes=#<struct Attributes name="Pedro", preferredLanguage="es", telephoneNumber="5555555", timeZone="Madrid">> 
user.to_h.to_json 
# => "{\"email\":\"[email protected]\",\"service\":\"coolService\",\"preferredLanguage\":\"es\",\"attributes\":\"#<struct Attributes name=\\\"Pedro\\\", preferredLanguage=\\\"es\\\", telephoneNumber=\\\"5555555\\\", timeZone=\\\"Madrid\\\">\"}" 
Oj.dump user, mode: :compat 
# => "\"#<struct User email=\\\"[email protected]\\\", service=\\\"coolService\\\", preferredLanguage=\\\"es\\\", attributes=#<struct Attributes name=\\\"Pedro\\\", preferredLanguage=\\\"es\\\", telephoneNumber=\\\"5555555\\\", timeZone=\\\"Madrid\\\">>\"" 

隨着to_h.to_json我得到的屬性的字符串對象,並與OJ,這不是有效的JSON。而且我還有一個問題,有從Java任何GSON,傑克遜庫如果你使用的ActiveSupport(導軌)的作品在紅寶石

回答

1

以同樣的方式,你會得到這樣的開箱。正如你似乎可以用準系統紅寶石,只是做遞歸:

hashify = lambda do |struct| 
    as_hash = struct.to_h 
    struct_keys = as_hash.select { |_, v| v.is_a? Struct }.map(&:first) 
    struct_keys.each { |key| as_hash[key] = hashify.(as_hash[key]) } 
    as_hash 
end 

hashify.(user).to_json 
    # => "{\"email\":\"[email protected]\",\"service\":\"coolService\",\"preferredLanguage\":\"es\",\"attributes\":{\"name\":\"Pedro\",\"preferredLanguage\":\"es\",\"telephoneNumber\":\"5555555\",\"timeZone\":\"Madrid\"}}" 

至於GSON,似乎有a wrapper for Ruby,但我不認爲這是廣泛使用。 Rails的猴子補丁行爲足以滿足99.99%的可能用途。它還可以讓你定義你的自定義序列化器,如果你想改變它。