go data_error ai_generated true

proto: (line 1:14): unknown field "userName"

ID: go/protobuf-json-unknown-field

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
0Evidence
2024-11-18First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
google.golang.org/protobuf 1.28+ active

Root Cause

protojson.Unmarshal encountered a JSON key that does not match any field in the target message. protobuf JSON uses either the proto field name (snake_case) or the lowerCamelCase JSON name; using an unrelated casing fails.

generic

中文

protojson.Unmarshal 遇到了与目标消息任何字段都不匹配的 JSON 键。protobuf JSON 使用 proto 字段名(snake_case)或 lowerCamelCase 的 JSON 名;使用不相关的命名会失败。

Workarounds

  1. 90% success
    opts := protojson.UnmarshalOptions{DiscardUnknown: true}
    if err := opts.Unmarshal(data, msg); err != nil {
        return err
    }
  2. 88% success
    // .proto: string user_name = 1;
    // JSON accepts either:
    // {"user_name":"alice"}  or  {"userName":"alice"}

Dead Ends

Common approaches that don't work:

  1. 80% fail

    encoding/json ignores protobuf-specific semantics (oneofs, well-known types) and produces incorrect values.

  2. 60% fail

    Fragile and breaks for nested messages, repeated fields, and oneofs; also loses type info.