Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将嵌套结构转换为JSON_Json_Ruby - Fatal编程技术网

将嵌套结构转换为JSON

将嵌套结构转换为JSON,json,ruby,Json,Ruby,我找到了相反的答案,但没有找到嵌套结构到JSON的方式 假设我有这个ruby结构 Attributes = Struct.new :name, :preferredLanguage, :telephoneNumber, :timeZone User = Struct.new :email, :service, :preferredLanguage, :attributes 我为属性创建结构 attributes = Attributes.new "Pedro", "es", "5555555"

我找到了相反的答案,但没有找到嵌套结构到JSON的方式

假设我有这个ruby结构

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\\\">\"" 

使用
to_h.to_json
我得到attributes对象的字符串,而使用oj,这不是有效的json。我还有另一个问题,java中的任何GSON、jackson库在ruby中的工作方式都是相同的,如果您使用ActiveSupport(Rails),您可以开箱即用。由于您似乎正在使用barebones Ruby,所以只需递归地执行即可:

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\":\"Pedro@email.com\",\"service\":\"coolService\",\"preferredLanguage\":\"es\",\"attributes\":{\"name\":\"Pedro\",\"preferredLanguage\":\"es\",\"telephoneNumber\":\"5555555\",\"timeZone\":\"Madrid\"}}"
至于GSON,似乎有,但我不认为它被广泛使用。Rails的猴子补丁行为足以满足99.99%的可能用途。如果要更改自定义序列化程序,还可以使用它定义自定义序列化程序

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\":\"Pedro@email.com\",\"service\":\"coolService\",\"preferredLanguage\":\"es\",\"attributes\":{\"name\":\"Pedro\",\"preferredLanguage\":\"es\",\"telephoneNumber\":\"5555555\",\"timeZone\":\"Madrid\"}}"