从 JSON 参数创建 Granite 模型

Create Granite model from JSON params

我希望发生的事情:有人可以使用参数向 users/new 发出 post 请求,我想从 [=27] 创建一个 User 对象=] 参数.

在自述文件中,它给出了这个例子:

foo = Foo.from_json(%({"name": "Granite1"}))

但是当我尝试这样做时,我得到了这个编译时错误:

in /usr/local/Cellar/crystal/0.26.1/src/json/pull_parser.cr:13: no 
overload matches 'JSON::Lexer.new' with type Hash(String, Array(JSON::Any) | Bool | Float64 | Hash(String, JSON::Any) | Int64 | String | Nil)

Overloads are:
- JSON::Lexer.new(string : String)
- JSON::Lexer.new(io : IO)
- JSON::Lexer.new()

@lexer = Lexer.new input
               ^~~

这是 env.params.json 登录到控制台时的样子:

{"name" => "test",
 "username" => "tester",
 "email" => "test",
 "password" => "test"}

如有任何帮助,我们将不胜感激。

编译器在这里引导您朝着正确的方向前进。看起来您正在传递一个变量,该变量在编译时具有 Hash(String, V) 类型,其中 V 是其中一种类型

  • Array(JSON::Any)
  • Bool
  • Float64
  • Hash(String, JSON::Any)
  • Int64
  • String
  • Nil

期望的是[=55的String(或IO对象,类似于String) =].这就是您在示例中所拥有的。 %(foo) 是创建 String "foo" 的另一种方法(有关详细信息,请参阅指南中的 "Percent string literals")。他们在这里使用它是因为它可以让你避免转义 JSON.

中使用的双引号

根据 Crystal 为您的参数提供的编译时类型,我猜测它已经从 JSON 转换为 Crystal Hash。仔细检查你没有解析它两次。

没有看到来源,我无法提供更多信息,但希望对您有所帮助。