如何将解析的 JSON 映射为 JSON::Any
键入自定义对象?
就我而言,我正在开发聊天客户端。聊天 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
显然,
Object.from_json
只能接受String
JSON,但未解析 JSON。就我而言 data
是 JSON::Any
目的。脏修复
Types::Update.from_json(data.to_json)
有效,但看起来很荒谬。将 JSON 对象映射到保留所有嵌套结构的自定义类型的正确方法是什么?
最佳答案
JSON.mapping
与 JSON.parse
不能很好地配合使用.要解决您的问题,您可以创建另一个映射 Types::Result
并使用 Object.from_json
解析一个洞 json使用起来更加方便:
module Types
class Message
JSON.mapping(
message_id: Int32,
text: String
)
end
class Update
JSON.mapping(
update_id: Int32,
message: Message
)
end
class Result
JSON.mapping(
success: { key: "ok", type: Bool },
updates: { key: "result", type: Array(Update) }
)
end
end
result = Types::Result.from_json string_json
result.success # => true
result.updates.first.message.text # => "hey"
关于crystal-lang - 如何将 JSON::Any 映射到 Crystal 语言中的自定义对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48016381/