David Razzetti
David Razzetti

Reputation: 167

Why is an exception thrown during JSON de-serialization of protobuf3 well-known types?

Using Google.Protobuf Nuget package version 3.4.1

In its simplest form, I have a Google protocol-buffers message defined like this:

syntax = "proto3";
package tests;
option csharp_namespace = "MyTests";

import "wrappers.proto";

message Foo {
    .google.protobuf.Int32Value NullableInt = 1;
}

I compile it to C# code using Google's protoc tool from Google.Protobuf.Tools version 3.4.0.

When I instantiate an instance of Foo and serialize it to a string using the Google.Protobuf.JsonFormatter I get a sensible result, which is "{ "NullableInt": 5 }". When I de-serialize this back into a Foo instance using Google.Protobuf.JsonParser, the parser throws a System.InvalidCastException stating "Unable to cast object of type 'System.Int32' to type 'Google.Protobuf.WellKnownTypes.Int32Value'."

Why is this exception being thrown? Am I doing something stupid?

Here is the code that I am running:

[Test]
public void TestRoundTripInt32Value()
{
    var foramtter = new JsonFormatter(new JsonFormatter.Settings(false));
    var foo = new Foo { NullableInt = new Int32Value {Value = 5} };
    var str = foramtter.Format(foo);
    Console.WriteLine(str);
    var parser = new JsonParser(new JsonParser.Settings(100));
    var foo2 = parser.Parse<Foo>(str);  // <= Throws!
    Assert.That(foo2, Is.EqualTo(foo));
}

Upvotes: 0

Views: 551

Answers (1)

David Razzetti
David Razzetti

Reputation: 167

See: https://groups.google.com/forum/#!topic/protobuf/w6RdxtSDswk

John Skeet demonstrated that the way the external proto-files were being imported was the cause of the issue. The correct way to do it is not obvious or clearly documented.

Upvotes: 0

Related Questions