Преглед изворни кода

Ruby JSON encoding omits zero-length repeated fields by default.

This makes it behave the same way as the other implementations.
It is also nice to always encode an empty message as {}.
Ewout пре 7 година
родитељ
комит
7b8f571756
2 измењених фајлова са 7 додато и 1 уклоњено
  1. 3 1
      ruby/ext/google/protobuf_c/encode_decode.c
  2. 4 0
      ruby/tests/basic.rb

+ 3 - 1
ruby/ext/google/protobuf_c/encode_decode.c

@@ -963,13 +963,15 @@ static void putary(VALUE ary, const upb_fielddef *f, upb_sink *sink,
 
   if (ary == Qnil) return;
 
+  size = NUM2INT(RepeatedField_length(ary));
+  if (size == 0 && !emit_defaults) return;
+
   upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);
 
   if (upb_fielddef_isprimitive(f)) {
     sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
   }
 
-  size = NUM2INT(RepeatedField_length(ary));
   for (int i = 0; i < size; i++) {
     void* memory = RepeatedField_index_native(ary, i);
     switch (type) {

+ 4 - 0
ruby/tests/basic.rb

@@ -1259,6 +1259,10 @@ module BasicTest
       Foo.encode_json(Foo.new(bar: bar, baz: [baz1, baz2]))
     end
 
+    def test_json_empty
+      assert TestMessage.encode_json(TestMessage.new) == '{}'
+    end
+
     def test_json_emit_defaults
       # TODO: Fix JSON in JRuby version.
       return if RUBY_PLATFORM == "java"