proto3 JSON: Serialize integer floats and doubles as integers (#695)
This is not required by the spec, but it seems to be more consistent
with how other libraries in other languages generate JSON.
Internally this change was made in cl/405998525.
diff --git a/protobuf/lib/src/protobuf/proto3_json.dart b/protobuf/lib/src/protobuf/proto3_json.dart
index 052d10c..d818014 100644
--- a/protobuf/lib/src/protobuf/proto3_json.dart
+++ b/protobuf/lib/src/protobuf/proto3_json.dart
@@ -67,6 +67,9 @@
if (value.isInfinite) {
return value.isNegative ? negativeInfinity : infinity;
}
+ if (fieldValue.toInt() == fieldValue) {
+ return fieldValue.toInt();
+ }
return value;
case PbFieldType._UINT64_BIT:
return (fieldValue as Int64).toStringUnsigned();
diff --git a/protoc_plugin/test/proto3_json_test.dart b/protoc_plugin/test/proto3_json_test.dart
index 606f338..633a12a 100644
--- a/protoc_plugin/test/proto3_json_test.dart
+++ b/protoc_plugin/test/proto3_json_test.dart
@@ -2,6 +2,7 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
+import 'dart:convert' show jsonEncode;
import 'dart:core' hide Duration;
import 'package:fixnum/fixnum.dart';
@@ -1253,6 +1254,7 @@
var proto = TestAllTypes()..optionalDouble = 5.0;
expect(TestAllTypes()..mergeFromProto3Json(json), proto);
expect(proto.toProto3Json(), json);
+ expect(jsonEncode(proto.toProto3Json()), '{"optionalDouble":5}');
});
test('Infinity', () {