1 package OpenSRF::Utils::JSON;
3 use vars qw/%_class_map/;
5 my $parser = JSON::XS->new;
6 $parser->ascii(1); # output \u escaped strings
7 $parser->allow_nonref(1);
9 sub register_class_hint {
12 $_class_map{hints}{$args{hint}} = \%args;
13 $_class_map{classes}{$args{name}} = \%args;
19 return $_class_map{hints}{$hint}{name}
25 return $_class_map{classes}{$class}{hint}
28 sub _json_hint_to_class {
32 return $_class_map{hints}{$hint}{name} if (exists $_class_map{hints}{$hint});
34 $type = 'hash' if ($type eq '}');
35 $type = 'array' if ($type eq ']');
37 OpenSRF::Utils::JSON->register_class_hint(name => $hint, hint => $hint, type => $type);
43 my $JSON_CLASS_KEY = '__c';
44 my $JSON_PAYLOAD_KEY = '__p';
47 my( $class, $string ) = @_;
48 my $perl = $class->rawJSON2perl($string);
49 return $class->JSONObject2Perl($perl);
53 my( $class, $obj ) = @_;
54 my $json = $class->perl2JSONObject($obj);
55 return $class->rawPerl2JSON($json);
62 if( $ref eq 'HASH' ) {
63 if( defined($obj->{$JSON_CLASS_KEY})) {
64 my $cls = $obj->{$JSON_CLASS_KEY};
67 if( $obj = $class->JSONObject2Perl($obj->{$JSON_PAYLOAD_KEY}) ) {
68 $cls = $class->lookup_class($cls) || $cls;
69 return bless(\$obj, $cls) unless ref($obj);
70 return bless($obj, $cls);
74 $obj->{$_} = $class->JSONObject2Perl($obj->{$_}) for (keys %$obj);
75 } elsif( $ref eq 'ARRAY' ) {
76 $obj->[$_] = $class->JSONObject2Perl($obj->[$_]) for(0..scalar(@$obj) - 1);
86 return $obj unless $ref;
89 if(UNIVERSAL::isa($obj, 'HASH')) {
91 $newobj->{$_} = $class->perl2JSONObject($obj->{$_}) for (keys %$obj);
92 } elsif(UNIVERSAL::isa($obj, 'ARRAY')) {
94 $newobj->[$_] = $class->perl2JSONObject($obj->[$_]) for(0..scalar(@$obj) - 1);
97 if($ref ne 'HASH' and $ref ne 'ARRAY') {
98 $ref = $class->lookup_hint($ref) || $ref;
99 $newobj = {$JSON_CLASS_KEY => $ref, $JSON_PAYLOAD_KEY => $newobj};
109 return undef unless defined $json and $json !~ /^\s*$/o;
110 return $parser->decode($json);
114 my ($class, $perl) = @_;
115 return $parser->encode($perl);