首页 文章

将水晶对象包装到JSON中的自定义根对象中

提问于
浏览
0

我有一个类似以下的课程

class Foo 
  JSON.mapping(
    bar: String,
    baz: String,
  )
end

我知道我可以通过在JSON.mapping中指定 {root: "name of node"} 来包装JSON对象中的单个属性 . 但有没有办法为整个 Foo 课程做到这一点?

那么输出看起来像这样?

{
  "foo": {
    "bar": "",
    "baz": ""
  }
}

2 回答

  • 1

    没有方法可以做到,但你可以这样做:

    require "json"
    
    class Foo
      JSON.mapping(
        bar: String,
        baz: String,
      )
    
      def initialize(@bar : String, @baz : String)
      end
    end
    
    foo = Foo.new("r", "z")
    json = {foo: foo}.to_json
    puts json
    
  • 0

    作为我的评论的替代方法,您还可以覆盖 Footo_json 方法:

    def to_json(builder : JSON::Builder)
      builder.object do
        builder.field "foo" do
          previous_def
        end
      end
    end
    

    https://carc.in/#/r/286q

相关问题