【问题标题】:Why is an exception thrown during JSON de-serialization of protobuf3 well-known types?为什么在对protobuf3知名类型进行JSON反序列化时会抛出异常?
【发布时间】:2017-10-16 14:21:51
【问题描述】:

使用 Google.Protobuf Nuget 包版本 3.4.1

在其最简单的形式中,我定义了一个 Google 协议缓冲区消息,如下所示:

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

import "wrappers.proto";

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

我使用来自 Google.Protobuf.Tools 版本 3.4.0 的 Google protoc 工具将其编译为 C# 代码。

当我实例化 Foo 的实例并使用 Google.Protobuf.JsonFormatter 将其序列化为字符串时,我得到了一个合理的结果,即 "{ "NullableInt": 5 }"。当我使用 Google.Protobuf.JsonParser 将其反序列化回 Foo 实例时,解析器会抛出 System.InvalidCastException,说明“无法将 'System.Int32' 类型的对象转换为 'Google.Protobuf.WellKnownTypes.Int32Value'。 "

为什么会抛出这个异常?我在做傻事吗?

这是我正在运行的代码:

[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));
}

【问题讨论】:

    标签: json protocol-buffers-3


    【解决方案1】:

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

    John Skeet 演示了导入外部原始文件的方式是问题的原因。正确的做法并不明显或没有明确记录。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-31
      • 1970-01-01
      • 1970-01-01
      • 2020-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多