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(導軌)的作品在紅寶石