From 4fed0b515fb18b0ffc6f5d382f38e2a1b39912dd Mon Sep 17 00:00:00 2001 From: Jon Skeet Date: Fri, 31 Jul 2015 10:33:31 +0100 Subject: Fix JSON formatting to always emit fields in field order, including oneofs --- csharp/src/Google.Protobuf/JsonFormatter.cs | 35 +++++------------------------ 1 file changed, 5 insertions(+), 30 deletions(-) (limited to 'csharp/src/Google.Protobuf') diff --git a/csharp/src/Google.Protobuf/JsonFormatter.cs b/csharp/src/Google.Protobuf/JsonFormatter.cs index 438af4df..d9783fc4 100644 --- a/csharp/src/Google.Protobuf/JsonFormatter.cs +++ b/csharp/src/Google.Protobuf/JsonFormatter.cs @@ -145,13 +145,14 @@ namespace Google.Protobuf var accessor = field.Accessor; // Oneofs are written later // TODO: Change to write out fields in order, interleaving oneofs appropriately (as per binary format) - if (field.ContainingOneof != null) + if (field.ContainingOneof != null && field.ContainingOneof.Accessor.GetCaseFieldDescriptor(message) != field) { continue; } - // Omit default values unless we're asked to format them + // Omit default values unless we're asked to format them, or they're oneofs (where the default + // value is still formatted regardless, because that's how we preserve the oneof case). object value = accessor.GetValue(message); - if (!settings.FormatDefaultValues && IsDefaultValue(accessor, value)) + if (field.ContainingOneof == null && !settings.FormatDefaultValues && IsDefaultValue(accessor, value)) { continue; } @@ -170,33 +171,7 @@ namespace Google.Protobuf builder.Append(": "); WriteValue(builder, accessor, value); first = false; - } - - // Now oneofs - foreach (var oneof in message.Descriptor.Oneofs) - { - var accessor = oneof.Accessor; - var fieldDescriptor = accessor.GetCaseFieldDescriptor(message); - if (fieldDescriptor == null) - { - continue; - } - object value = fieldDescriptor.Accessor.GetValue(message); - // Omit awkward (single) values such as unknown enum values - if (!fieldDescriptor.IsRepeated && !fieldDescriptor.IsMap && !CanWriteSingleValue(fieldDescriptor, value)) - { - continue; - } - - if (!first) - { - builder.Append(", "); - } - WriteString(builder, ToCamelCase(fieldDescriptor.Name)); - builder.Append(": "); - WriteValue(builder, fieldDescriptor.Accessor, value); - first = false; - } + } builder.Append(first ? "}" : " }"); } -- cgit v1.2.3