2012-07-31 150 views
4

我嘗試了很多時間將perl對象轉換爲JSON字符串。但我仍然無法找到。我使用JSYNC。但我看到它有一些問題。然後我在perl中使用JSON模塊。 這是我的代碼。
如何將perl對象轉換爲json字符串

my $accountData = AccountsData ->new(); 
$accountData->userAccountsDetail(@userAccData); 
$accountData->creditCardDetail(@userCrData); 
my $json = to_json($accountData,{allow_blessed=>1,convert_blessed=>1}); 
print $json."\n"; 

當我運行代碼,它打印null。就是有沒有搞錯我都做了些什麼?

+1

請在www.cpan.org檢查模塊JSON :: XS或JSON – 2012-07-31 12:13:34

回答

8

第一個版本:

use JSON::XS; 
use Data::Structure::Util qw/unbless/; 


sub serialize { 
    my $obj = shift; 
    my $class = ref $obj; 
    unbless $obj; 
    my $rslt = encode_json($obj); 
    bless $obj, $class; 
    return $rslt; 
} 

sub deserialize { 
    my ($json, $class) = @_; 
    my $obj = decode_json($json); 
    return bless($obj, $class); 
} 

第二個版本:

package SerializablePoint; 

use strict; 
use warnings; 
use base 'Point'; 

sub TO_JSON { 
    return { %{ shift() } }; 
} 

1; 

package main; 

use strict; 
use warnings; 
use SerializablePoint; 
use JSON::XS; 

my $point = SerializablePoint->new(10, 20); 

my $json = JSON::XS->new->convert_blessed->encode($point); 
print "$json\n"; 
print "point: x = ".$point->get_x().", y = ".$point->get_y()."\n"; 
+3

直接使用'JSON'而不是'JSON :: XS'通常會更好。它將使用'JSON :: XS'(如果可用),然後回退到純Perl版本。 – Quentin 2012-07-31 12:18:07

+1

非常感謝。我使用JSON :: XS並理清了我的問題。 – Amila 2012-07-31 13:05:08

+1

對於一個「漂亮」的輸出:'使用JSON qw(encode_json)'(而不是JSON :: XS),然後:'sub serialize {my $ json = JSON-> new-> utf8; ...我的$ rslt = $ json-> pretty-> encode($ obj); ''。 – lepe 2016-01-08 05:05:32

2

the docs,你的對象必須提供TO_JSON方法,其中to_json會再使用。它也似乎意味着如果您想避免提供自己的TO_JSON方法,則可以在轉換之前調用JSON -convert_blessed_universally;,但文檔指出這是一個實驗性功能。

相關問題