如何将 JSON::Any 映射到 Crystal 语言的自定义对象?

How to map JSON::Any to custom Object in Crystal language?

如何将已解析的 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。在我的例子中 dataJSON::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"