SOAP从哈希创建JSON并从客户端解码

时间:2012-04-07 05:30:44

标签: json perl soap hash

我正在使用soap制作网络服务。我坚持试图找出使用perl将哈希转换为JSON。现在我正在测试它与客户端,我正在尝试打印出JSON-所以我不确定我的问题是在服务器端还是客户端。

这是我的服务器端代码。

 #create hash
 my %hash_to_encode = (
    weigh => $weight,
    price => $price,
    unit  => $unit,
    picture=> $picture,
    amount => $amount,
    dimensions => $dimensions,
    country => $country,
    description => $description,
    name => $name,
    category => $category,
    comment => $comment,
    expires => $expires
  );

 my $json_string = JSON->new->utf8->encode(%hash_to_encode);

return $json_string;

My client side code:
#! /usr/bin/perl -w
use CGI qw(:standard);
use SOAP::Lite;
use JSON;
print "Content-type: text/html\n\n";

my $exhibitID = '13';
my $username = 'us43';
my $password = 'green4356';
my $link = 'its a secret :P';
my $namespace = 'also a sewcret';
#The soap call works (i have other functions and they work as expected so dont worry about this part.
my $mySoap = SOAP::Lite
 -> uri($link)
 -> proxy($namespace);

#This is where the error lies.
my $result = $mySoap->status($exhibitID, $username, $password)->result;
print "Json String: $result";

#my $jsonString= JSON->new->utf8->decode($result);
#print "Status is: $jsonString";

print "<p> Finished status</p>";

感谢您的帮助:)

1 个答案:

答案 0 :(得分:3)

my $json_string = JSON->new->utf8->encode(\%hash_to_encode);

您需要提供哈希引用,而不仅仅是编码函数的哈希值。

要这样做,要么像我上面那样添加反斜杠,要么改变下面的定义(只做两个中的一个......)

my $hash_to_encode = {
weigh => $weight,
price => $price,
unit  => $unit,
picture=> $picture,
amount => $amount,
dimensions => $dimensions,
country => $country,
description => $description,
name => $name,
category => $category,
comment => $comment,
expires => $expires
};