如何将解析后的JSON映射为JSON::Any
类型到自定义对象?
就我而言,我正在研究聊天客户端。 Chat API可以使用以下JSON响应请求:
{"ok" => true,
"result" =>
[{"update_id" => 71058322,
"message" =>
{"message_id" => 20,
"from" => "Benjamin",
"text" => "hey"}}]}
在我的API客户端代码中的某处,我解析这些JSON以执行一些基本的运行状况检查并将结果传递给响应使用者。在消费者中,我迭代result
数组并尝试将每个更新转换为适当的对象:
module Types
class Update
JSON.mapping({
update_id: {type: Int32},
message: {type: Message},
})
end
end
module Types
class Message
JSON.mapping({
message_id: Int32,
date: Int32,
text: String,
})
end
end
return unless response["ok"]
response["result"].each do |data|
update = Types::Update.from_json(data)
end
不幸的是,最后一行会导致编译错误:
no overload matches 'JSON::Lexer.new' with type JSON::Any
显然,qazxsw poi只能接受qazxsw poi JSON,但不能解析JSON。在我的情况下Object.from_json
是String
对象。
肮脏的修复data
工作,但它看起来很荒谬。
将JSON对象映射到保留所有嵌套结构的自定义类型的正确方法是什么?
JSON::Any
与Types::Update.from_json(data.to_json)
不能很好地协同工作。要解决您的问题,您可以创建另一个映射JSON.mapping
并使用JSON.parse
解析一个孔json,使用起来更方便:
Types::Result