【发布时间】:2014-09-30 12:20:44
【问题描述】:
我在使用用于 JSON 和 JSON 数组的内置 Perl Dancer 序列化程序时遇到问题。
我在 app.pl 文件中激活了序列化程序:
#!/usr/bin/env perl
use Dancer;
use main;
set serializer => 'JSON';
dance;
在模块本身中,我测试了这样的 JSON 解析:
post '/test/' => sub {
my $params = request->params;
debug('Test: ', $params);
};
现在我想确保按预期解析 JSON,因此我尝试使用 cURL 来了解序列化程序的工作方式:
curl -H "Content-Type: application/json" -X POST http://localhost:3000/test/ -d '{ "Name" : "foo", "email" : "bar" }'
结果如预期:
Test: {'Name' => 'foo','email' => 'bar'}
但是试图发送一个数组:
curl -H "Content-Type: application/json" -X POST http://localhost:3000/test/ -d '[{ "Name" : "foo", "email" : "bar" }]'
导致:
Test: {}
我希望序列化程序返回一个数组引用,但它似乎返回一个空哈希。我尝试以相反的方式使用序列化程序,但编码 JSON 似乎按预期工作。我做错了什么?
【问题讨论】:
-
这是做什么的?
curl -H "Content-Type: application/json" -X POST http://localhost:3000/test/ -d '{ "Name" : "foo", "email" : "bar" },{ "Name" : "baz", "email" : "baz@baz.newt" }' -
对不起,Dancer doc on params 表示它在标量上下文中处理哈希。思想也许可以迫使它散列。
-
无论如何谢谢你——很可能我使用了错误的方法来访问我发送的 JSON。我试图创建一个类似的 JSON:
curl -H "Content-Type: application/json" -X POST http://localhost:300/test/ -d '{ "testA" : { "Name" : "foo", "email" : "bar" }, "testB" : { "Name" : "baz", "email" : "baz@baz.newt" }}'这会返回预期的:Test: {'testA' => {'Name' => 'foo','email' => 'bar'},'testB' => {'Name' => 'baz','email' => 'baz@baz.newt'}}但将其放入数组[ { "Name" : "foo", "email" : "bar" }, { "Name" : "baz", "email" : "baz@baz.newt" }]仍然会返回Test: {}
标签: arrays json perl serialization dancer