You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Google.Protobuf.JsonFormatter转Protobuf为JSON遇oneof错误求助

解决Protobuf转JSON时的Oneof字段错误

错误原因

你碰到的System.InvalidOperationException: 'Value message must contain a value for the oneof.'错误,是因为你的Protobuf对象里包含oneof类型字段,但这个字段没有设置任何可选值,而默认的JsonFormatter要求oneof字段必须有值才能完成序列化。

解决方案

方案1:确保Oneof字段已赋值

检查response对应的Protobuf定义,找到其中的oneof字段,确保代码里已经为该oneof的某一个可选字段赋值。比如你的Protobuf定义如果是这样:

message Value {
  oneof kind {
    int32 int_val = 1;
    string str_val = 2;
    bool bool_val = 3;
  }
}

那在生成的C#代码中,你需要明确给int_val、str_val或bool_val其中一个赋值,不能让oneof处于无值状态。

方案2:修改JsonFormatter设置,忽略未赋值的Oneof

如果业务逻辑允许oneof字段为空,可以修改JsonFormatter的配置,允许忽略未赋值的oneof字段,避免报错。修改后的代码如下:

// 启用忽略未赋值oneof的设置
var formatterSettings = JsonFormatter.Settings.Default.WithIgnoreMissingOneofs(true);
var formatter = new JsonFormatter(formatterSettings);
string json = formatter.Format(response);

这样即使oneof字段没有赋值,也能正常将Protobuf对象序列化为JSON,此时oneof对应的字段不会出现在JSON结果中。

内容的提问来源于stack exchange,提问作者Юрій Ізьо

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 22:12:06