perl6类to-json排除属性

时间:2018-11-01 22:56:35

标签: json class perl6

我一直在疯狂地尝试找到一个可以与嵌套对象(特别是类)一起使用的模块。有一些模块非常接近,但是我不想将属性设置为null来跳过不需要的值。

如果我可以编写一个TO_JSON方法或返回一个将被模块编组的结构,那将是很棒的。或者,只需对我们不希望包含在最终JSON文档中的属性使用“ json-skip”。

类似的东西:

class Something {
   has Str $.foo;
   has Str $.bar is json-skip;

}

class Something { 
   has Str $.foo;
   has Str $.bar;

   method TO_JSON {
      return {
          foo => $.foo
      }
   }
}

JSON :: Tiny,JSON :: Fast,JSON :: Marshal等...都适用于单个结构,甚至适用于嵌套实例,但是排除属性目前使我难以理解。

最后,我想做些类似的事情:

my $json-document = to-json(@nestedInstances);

2 个答案:

答案 0 :(得分:9)

to-json中的子JSON::Tiny是多个。这样您就可以为您的课堂重新定义行为。

multi sub to-json ( Something $_ ) {
    to-json 'foo' => .foo
}

下面的示例可能可以根据需要工作。

use JSON::Tiny;

class Something { 
   has Str $.foo;
   has Str $.bar;

   method TO_JSON {
      return {
          foo => $.foo
      }
   }
}

multi sub to-json ( $_ where *.can('TO_JSON') ) {
    to-json .TO_JSON
}

my Something $sth .=  new: :foo<interest>, :bar<no_interest>;

say to-json [$sth,2, :$sth];

输出:

[ { "foo" : "interest" }, 2, { "sth" : { "foo" : "interest" } } ]

答案 1 :(得分:2)

以上答案是已接受的答案,我在JSON :: Tiny github存储库中将其设为问题。下面的代码只是为了阐明对于perl6来说我们这些新手正在发生的事情:

use JSON::Tiny;
# The JSON::Tiny module has a bunch of multi to-json subs.
# Here we are creating/adding one that takes an instance that can do "TO_JSON", i.e. has a TO_JSON method
multi to-json ( $_ where *.can('TO_JSON') ) {
   # Execute the method TO_JSON on the passed instance and use one of
   #  the other to-json subs in the JSON::Tiny module that supports the
   #  returned structure
   to-json $_.TO_JSON
}

class Something { 
   has Str $.foo;
   has Str $.bar;

   method TO_JSON {
      return {
          foo => $.foo
      }
   }
}

my Something $sth = Something.new( foo => 'Interested', bar => 'Not interested' );

# The lexically scoped to-json sub above is used because it takes an argument that implements the TO_JSON method
say to-json $sth;

输出:

{ "foo" : "Interested" }