diff --git a/csharp/src/Google.Protobuf.Test/JsonFormatterTest.cs b/csharp/src/Google.Protobuf.Test/JsonFormatterTest.cs index 77da66351e..61adc1da78 100644 --- a/csharp/src/Google.Protobuf.Test/JsonFormatterTest.cs +++ b/csharp/src/Google.Protobuf.Test/JsonFormatterTest.cs @@ -900,6 +900,42 @@ namespace Google.Protobuf AssertWriteValue(value, "[\n 1,\n 2,\n 3\n]", JsonFormatter.Settings.Default.WithIndentation()); } + [Test] + public void WriteValueWithIndentation_Any() + { + var registry = TypeRegistry.FromMessages(ForeignMessage.Descriptor); + var formatter = JsonFormatter.Settings.Default.WithIndentation().WithTypeRegistry(registry); + + var nestedMessage = new ForeignMessage { C = 1 }; + var value = Any.Pack(nestedMessage); + const string expectedJson = @" +{ + '@type': 'type.googleapis.com/protobuf_unittest3.ForeignMessage', + 'c': 1 +}"; + + AssertWriteValue(value, expectedJson, formatter); + } + + [Test] + public void WriteValueWithIndentation_NestedAny() + { + var registry = TypeRegistry.FromMessages(ForeignMessage.Descriptor); + var formatter = JsonFormatter.Settings.Default.WithIndentation().WithTypeRegistry(registry); + + var nestedMessage = new ForeignMessage { C = 1 }; + var value = new TestWellKnownTypes { AnyField = Any.Pack(nestedMessage) }; + const string expectedJson = @" +{ + 'anyField': { + '@type': 'type.googleapis.com/protobuf_unittest3.ForeignMessage', + 'c': 1 + } +}"; + + AssertWriteValue(value, expectedJson, formatter); + } + [Test] public void WriteValueWithIndentation_CustomIndentation() { diff --git a/csharp/src/Google.Protobuf/JsonFormatter.cs b/csharp/src/Google.Protobuf/JsonFormatter.cs index 77ca26e7cc..fbcc839707 100644 --- a/csharp/src/Google.Protobuf/JsonFormatter.cs +++ b/csharp/src/Google.Protobuf/JsonFormatter.cs @@ -481,6 +481,7 @@ namespace Google.Protobuf { } IMessage message = descriptor.Parser.ParseFrom(data); WriteBracketOpen(writer, ObjectOpenBracket); + MaybeWriteValueWhitespace(writer, indentationLevel + 1); WriteString(writer, AnyTypeUrlField); writer.Write(NameValueSeparator); WriteString(writer, typeUrl); @@ -489,9 +490,9 @@ namespace Google.Protobuf { writer.Write(ValueSeparator); WriteString(writer, AnyWellKnownTypeValueField); writer.Write(NameValueSeparator); - WriteWellKnownTypeValue(writer, descriptor, message, indentationLevel); + WriteWellKnownTypeValue(writer, descriptor, message, indentationLevel + 1); } else { - WriteMessageFields(writer, message, true, indentationLevel); + WriteMessageFields(writer, message, true, indentationLevel + 1); } WriteBracketClose(writer, ObjectCloseBracket, true, indentationLevel); }