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

问题描述 投票:4回答:1

如何将解析后的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_jsonString对象。

肮脏的修复data工作,但它看起来很荒谬。

将JSON对象映射到保留所有嵌套结构的自定义类型的正确方法是什么?

crystal-lang
1个回答
7
投票

JSON::AnyTypes::Update.from_json(data.to_json)不能很好地协同工作。要解决您的问题,您可以创建另一个映射JSON.mapping并使用JSON.parse解析一个孔json,使用起来更方便:

Types::Result
© www.soinside.com 2019 - 2024. All rights reserved.