aboutsummaryrefslogtreecommitdiffhomepage
path: root/csharp/src/Google.Protobuf/JsonFormatter.cs
diff options
context:
space:
mode:
authorGravatar Jon Skeet <jonskeet@google.com>2015-07-31 10:33:31 +0100
committerGravatar Jon Skeet <jonskeet@google.com>2015-07-31 10:34:20 +0100
commit4fed0b515fb18b0ffc6f5d382f38e2a1b39912dd (patch)
treed70d4359c06388d56342fb2be2f0b84d75eda2aa /csharp/src/Google.Protobuf/JsonFormatter.cs
parentfd02e45b2a2f38da25ee2d202ed911b684fe30ac (diff)
Fix JSON formatting to always emit fields in field order, including oneofs
Diffstat (limited to 'csharp/src/Google.Protobuf/JsonFormatter.cs')
-rw-r--r--csharp/src/Google.Protobuf/JsonFormatter.cs35
1 files changed, 5 insertions, 30 deletions
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 ? "}" : " }");
}