1 2use strict; 3use Test::More tests => 4; 4 5BEGIN { 6 $ENV{ PERL_JSON_BACKEND } = "JSON::backportPP"; 7} 8 9use JSON; 10 11my $json = JSON->new->convert_blessed; 12 13my $obj = OverloadedObject->new( 'foo' ); 14ok( $obj eq 'foo' ); 15is( $json->encode( [ $obj ] ), q{["foo"]} ); 16 17# rt.cpan.org #64783 18my $foo = bless {}, 'Foo'; 19my $bar = bless {}, 'Bar'; 20 21eval q{ $json->encode( $foo ) }; 22ok($@); 23eval q{ $json->encode( $bar ) }; 24ok(!$@); 25 26 27package Foo; 28 29use strict; 30use overload ( 31 'eq' => sub { 0 }, 32 '""' => sub { $_[0] }, 33 fallback => 1, 34); 35 36sub TO_JSON { 37 return $_[0]; 38} 39 40package Bar; 41 42use strict; 43use overload ( 44 'eq' => sub { 0 }, 45 '""' => sub { $_[0] }, 46 fallback => 1, 47); 48 49sub TO_JSON { 50 return overload::StrVal($_[0]); 51} 52 53 54package OverloadedObject; 55 56use overload 'eq' => sub { $_[0]->{v} eq $_[1] }, '""' => sub { $_[0]->{v} }, fallback => 1; 57 58 59sub new { 60 bless { v => $_[1] }, $_[0]; 61} 62 63 64sub TO_JSON { "$_[0]"; } 65 66