diff --git a/lib/google/apis/core/json_representation.rb b/lib/google/apis/core/json_representation.rb index ab28e04e1..4c78d361f 100644 --- a/lib/google/apis/core/json_representation.rb +++ b/lib/google/apis/core/json_representation.rb @@ -122,6 +122,24 @@ module Google include Representable::JSON feature JsonRepresentationSupport end + + module JsonObjectSupport + def self.included(base) + base.extend(ClassMethods) + end + + module ClassMethods + def from_json(json) + representation = self.const_get(:Representation) + representation.new(self.new).from_json(json, unwrap: self) + end + end + + def to_json + representation = self.class.const_get(:Representation) + representation.new(self).to_json(skip_undefined: true) + end + end end end end diff --git a/lib/google/apis/generator/templates/_representation_stub.tmpl b/lib/google/apis/generator/templates/_representation_stub.tmpl index b80cf6932..8882f2e04 100644 --- a/lib/google/apis/generator/templates/_representation_stub.tmpl +++ b/lib/google/apis/generator/templates/_representation_stub.tmpl @@ -7,6 +7,8 @@ class <%= cls.generated_class_name %> <%= indent(include('representation_stub', :cls => child_class), 2) -%> <% end -%> <% end -%> + + include Google::Apis::Core::JsonObjectSupport end <% elsif cls.items && cls.items._ref.nil? -%> <%= include('representation_stub', :cls => cls.items, :api => api) -%> diff --git a/spec/google/apis/generator/generator_spec.rb b/spec/google/apis/generator/generator_spec.rb index a771d80d4..07dd53283 100644 --- a/spec/google/apis/generator/generator_spec.rb +++ b/spec/google/apis/generator/generator_spec.rb @@ -120,6 +120,58 @@ RSpec.describe Google::Apis::Generator do it 'should define subresource methods' do expect(service.method(:list_thing_subthings)).to_not be_nil end + + context 'With the from_json method' do + let(:json) do + <