3

对我来说,在 Mojolicious 中解析 JSON 是不可能的。我更新了 Mojolicious 并在以下代码之前使用,但 JSON->new 已弃用。

my $json = Mojo::JSON->new;
my $user_request = $json->decode($c->req->body);
my $err = $json->error;

从教程中,我发现已经添加了 $self->req->json,但是对此的所有 POST 都会导致错误和无效代码。

 curl -H "Content-Type: application/json" --data @body.json http://localhost:3000/checkaddress

我的 body.json 看起来像这样

{
       'id': 1
}

这是我在 Mojolicious 中的 RESTful 代码

post '/checkaddress' => sub {
my $self = shift;
my $dump = $self->dumper($self->req->json);
};

控制台日志

[Sat Feb 20 08:23:27 2016] [debug] 200 OK (0.001688s, 592.417/s)
[Sat Feb 20 08:24:38 2016] [debug] POST "/checkaddress"
[Sat Feb 20 08:24:38 2016] [debug] Routing to a callback
[Sat Feb 20 08:24:38 2016] [debug] undef

从 Mojo::JSON 调用 $self->req->body 然后 decode_json 将导致

[error] Malformed JSON: Expected string while parsing object at line 1,  offset 5 at /home/aa/sempt2.pl line 15.

那么,现在如何正确解析 JSON 呢?

4

2 回答 2

6

这适用于 Mojolicious 6.25,是一个完整的示例:

package MyREST;
use Mojo::Base 'Mojolicious';

use Data::Dumper;

sub startup {
  my $app = shift;

  my $routes = $app->routes;

  $routes->post('/checkaddress' => sub {
    my $self = shift;
    my $data = $self->req->json;
    my $dump = $self->dumper($self->req->json);
    print STDERR $dump;
    $self->render(json => $data);
  });

}

1;

为了方便和可靠地测试一个小客户端脚本:

#!perl

use strict;
use warnings;

use Mojo::UserAgent;

my $ua = Mojo::UserAgent->new;

my $tx = $ua->post('http://localhost:3000/checkaddress' => json =>
  {
    'id'  => "1",
  }
);

该脚本避免了 JSON 编码问题。

更好的是,以 Mojolicious 风格编写测试。

于 2016-02-20T09:24:28.493 回答
5

我解决了!

{
   'id': 1
}

它需要更换为

{
  "id": 1
}

然后可以使用 id 访问

my $test = decode_json($self->req->body);
$test->{id};

和缩短的方式

my $test = $self->req->json;
$test->{id};

也在工作!

发生错误是因为错误的 json 编码 '',它需要是“”。希望它可以帮助某人。

于 2016-02-20T08:22:05.357 回答