我使用Rails 4.2.0和ActiveResource来实现服务器API的webclient。 我遇到的问题是服务器资源在属性名称中包含“@”和“@@”。因此,在创建ARes对象时,ActiveResource无法正确处理这些属性。 示例:服务器返回JSON数据:
{"@@artist"=>
{"@id"=>"some_text_id",
"@name"=>"Carman",
"@publisher"=>"Carmen radio",
"@category"=>"Music",
"@automaticallyGenerated"=>true,
"@@options"=>{"@public"=>true, "@enabled"=>false},
"_extended"=>{"@container"=>"Music box", "region"=>"Europe"}}}
在创建ARes对象之前重命名属性的变体:(从名称中删除'@'或将其替换为另一个符号)。在这种情况下,我需要在发送POST
,PUT
请求之前重新命名重命名属性(例如,调用resource.save
)例如。在名称的开头添加“@”或“@@”。
你能否提出更灵活,更漂亮的变体?
答案 0 :(得分:2)
我不知道你的输出是什么,但你可以使用这样的东西。 这只是一个例子。
input = {
"@@artist"=>
{"@id"=>"some_text_id",
"@name"=>"Carman",
"@publisher"=>"Carmen radio",
"@category"=>"Music",
"@automaticallyGenerated"=>true,
"@@options"=>{"@public"=>true, "@enabled"=>false},
"_extended"=>{"@container"=>"Music box", "region"=>"Europe"}
}
}
def transcode(hash)
result = {}
hash.each do |k, v|
result[k.gsub(/@*/, "")] = ( Hash === v ? transcode(v) : v )
end
result
end
output = transcode(input)
#{
# "artist" => {
# "id" => "some_text_id",
# "name" => "Carman",
# "publisher" => "Carmen radio",
# "category" => "Music",
# "automaticallyGenerated" => true,
# "options" => {
# "public" => true,
# "enabled" => false
# },
# "_extended" => {
# "container" => "Music box",
# "region" => "Europe"
# }
# }
#}
BACK
input = {
"@@artist"=>
{"@id"=>"some_text_id",
"@name"=>"Carman",
"@publisher"=>"Carmen radio",
"@category"=>"Music",
"@automaticallyGenerated"=>true,
"@@options"=>{"@public"=>true, "@enabled"=>false},
"_extended"=>{"@container"=>"Music box", "region"=>"Europe"}
}
}
def transcode(hash)
result = {}
hash.each do |k, v|
result[k.gsub(/@*/, "")] = ( Hash === v ? transcode(v) : v )
end
result
end
def transcode_back(hash, output)
result = {}
hash.each do |k, v|
value = output[k.gsub(/@*/, "")]
result[k] = ( Hash === value ? transcode_back(v, value) : value )
end
result
end
output = transcode(input)
# you can modify values
#output["artist"]["name"] = "CarmanNew"
result = transcode_back(input, output)
output == result # is same ?
# true