From 730c38ad8c11429bc7ea0310bc1b82f0831b42a6 Mon Sep 17 00:00:00 2001 From: Jon Skeet Date: Fri, 15 Jan 2016 10:41:56 +0000 Subject: Support (and test) numeric enum parsing in JSON --- csharp/src/Google.Protobuf.Test/JsonParserTest.cs | 20 ++++++++++++++++++++ csharp/src/Google.Protobuf/JsonParser.cs | 9 +++++++++ 2 files changed, 29 insertions(+) (limited to 'csharp') diff --git a/csharp/src/Google.Protobuf.Test/JsonParserTest.cs b/csharp/src/Google.Protobuf.Test/JsonParserTest.cs index 60c4d815..b8fe67f8 100644 --- a/csharp/src/Google.Protobuf.Test/JsonParserTest.cs +++ b/csharp/src/Google.Protobuf.Test/JsonParserTest.cs @@ -821,6 +821,26 @@ namespace Google.Protobuf Assert.Throws(() => parser63.Parse(data64)); } + [Test] + [TestCase("\"FOREIGN_BAR\"")] + [TestCase("5")] + public void EnumValid(string value) + { + string json = "{ \"singleForeignEnum\": " + value + " }"; + var parsed = TestAllTypes.Parser.ParseJson(json); + Assert.AreEqual(new TestAllTypes { SingleForeignEnum = ForeignEnum.FOREIGN_BAR }, parsed); + } + + [Test] + [TestCase("\"NOT_A_VALID_VALUE\"")] + [TestCase("100")] + [TestCase("5.5")] + public void Enum_Invalid(string value) + { + string json = "{ \"singleForeignEnum\": " + value + " }"; + Assert.Throws(() => TestAllTypes.Parser.ParseJson(json)); + } + /// /// Various tests use strings which have quotes round them for parsing or as the result /// of formatting, but without those quotes being specified in the tests (for the sake of readability). diff --git a/csharp/src/Google.Protobuf/JsonParser.cs b/csharp/src/Google.Protobuf/JsonParser.cs index f7ebd057..25afd0f2 100644 --- a/csharp/src/Google.Protobuf/JsonParser.cs +++ b/csharp/src/Google.Protobuf/JsonParser.cs @@ -608,6 +608,15 @@ namespace Google.Protobuf throw new InvalidProtocolBufferException($"Value out of range: {value}"); } return (float) value; + case FieldType.Enum: + CheckInteger(value); + var enumValue = field.EnumType.FindValueByNumber((int) value); + if (enumValue == null) + { + throw new InvalidProtocolBufferException($"Invalid enum value: {value} for enum type: {field.EnumType.FullName}"); + } + // Just return it as an int, and let the CLR convert it. + return enumValue.Number; default: throw new InvalidProtocolBufferException($"Unsupported conversion from JSON number for field type {field.FieldType}"); } -- cgit v1.2.3