Skip to content

pubgo/protoc-gen-go-json

Repository files navigation

protoc-gen-go-json

Go Reference CI Go Report Card

中文文档

A protoc plugin that generates json.Marshaler and json.Unmarshaler implementations for Go protobuf messages.

Features

  • 🚀 Lightweight - Generates clean and efficient code
  • 🔄 Recursive Support - Automatically handles nested message types
  • Standard Compatible - Uses official protojson package for compatibility
  • ⚙️ Configurable - Supports multiple customization options
  • 📦 Proto3 Optional - Supports proto3 optional feature

Installation

go install github.com/pubgo/protoc-gen-go-json@latest

Usage

Basic Usage

protoc --go_out=. --go-json_out=. your_proto_file.proto

With buf

Add to your buf.gen.yaml:

version: v2
plugins:
  - local: protoc-gen-go
    out: gen
    opt: paths=source_relative
  - local: protoc-gen-go-json
    out: gen
    opt:
      - paths=source_relative

Options

Option Default Description
enums_as_ints false Render enums as integers instead of strings
emit_defaults false Render fields with zero values
orig_name false Use original (.proto) name for fields
allow_unknown false Allow messages to contain unknown fields when unmarshaling
debug false Enable debug mode

Example

protoc --go-json_out=emit_defaults=true,orig_name=true:. your_proto_file.proto

Generated Output

For the following protobuf definition:

message User {
  string name = 1;
  int32 age = 2;
}

The plugin generates:

// MarshalJSON implements json.Marshaler
func (msg *User) MarshalJSON() ([]byte, error) {
    return protojson.MarshalOptions{
        UseEnumNumbers:  false,
        EmitUnpopulated: false,
        UseProtoNames:   false,
    }.Marshal(msg)
}

// UnmarshalJSON implements json.Unmarshaler
func (msg *User) UnmarshalJSON(b []byte) error {
    return protojson.UnmarshalOptions{
        DiscardUnknown: false,
    }.Unmarshal(b, msg)
}

Why This Plugin?

By default, Go structs generated by protoc-gen-go don't implement the standard library's json.Marshaler and json.Unmarshaler interfaces. This means that using the encoding/json package may result in field names and enum values being serialized in a way that doesn't conform to the protobuf JSON mapping specification.

The code generated by this plugin uses the official protojson package, ensuring:

  • Field names follow protobuf JSON mapping specification
  • Enum values are serialized as strings by default
  • Proper handling of oneof, optional, and other special fields
  • Consistency with protobuf JSON implementations in other languages

Dependencies

License

MIT License

About

一个 protobuf 编译器插件,为 Go 语言的 protobuf 消息自动生成 json.Marshaler 和 json.Unmarshaler 接口实现

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages