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

标签 crystal-lang

如何将解析的 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"

关于crystal-lang - 如何将 JSON::Any 映射到 Crystal 语言中的自定义对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48016381/

相关文章:

crystal-lang - 尝试运行 Crystal Spec 时找不到 -lxml2

crystal-lang - 在 windows 上编程和运行 crystal

arrays - 在 Crystal lang 中解析 JSON 对象数组

git - 碎片包和 Crystal 要忽略什么

database - Crystal - 类破坏方法

macos - ld : library not found for -lssl

crystal-lang - 如何配置JSON.mapping让Array of Strings Array变成Hash?

crystal-lang - 为什么 Crystal 不能在初始化程序中推断出这种类型?

crystal-lang - Crystal 语言:使用什么代替运行时 String::to_sym

crystal-lang - 运行 Crystal 程序时,程序收到但未处理信号 IOT (6)