0

I have a class like the following

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

I know that I can wrap single attributes in JSON objects by specifying {root: "name of node"} inside of JSON.mapping. But is there any way to do it for the entire Foo class?

So that the output would look like this?

{
  "foo": {
    "bar": "",
    "baz": ""
  }
}
Kilian
  • 2,122
  • 2
  • 24
  • 42

2 Answers2

1

There's no method to do it, but you can do this:

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
asterite
  • 2,906
  • 1
  • 14
  • 14
  • Interesting, thanks for the answer! The only problem I have now is that my question was a bit too abstract :/ The problems seems to now lie in the fact, that my object is already a nested object inside something else I'm calling #to_json on. I tried the naïve way of overwriting #to_json and returning `{foo: self}.to_json`, but that doesn't work. – Kilian Oct 07 '16 at 07:20
  • Then why don't you use `root` for the field with `Foo` on the enclosing object? – Johannes Müller Jun 21 '17 at 08:52
0

As an alternative to my comment, you can also overwrite the to_json method of Foo:

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

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

Johannes Müller
  • 5,581
  • 1
  • 11
  • 25