Protobuf: protoreflect.ProtoMessage does not implement protoiface.MessageV1 (missing ProtoMessage method)

Created on 15 May 2020  路  4Comments  路  Source: golang/protobuf

I'm doing a tutorial from Youtube. Can't proceed because of this error. All information required to debug is in image. go version: 1.14.3

Screen Shot 2020-05-15 at 9 59 22 PM

question

Most helpful comment

There's a mismatch going on, since the code is trying to pass a "google.golang.org/protobuf/proto".Message to "github.com/golang/protobuf/jsonpb".Marshaler.MarshalToString, which expects a "github.com/golang/protobuf/proto".Message.

This can be resolved by either:

I recommend the first solution:

package serializer

import (
    "google.golang.org/protobuf/encoding/protojson"
    "google.golang.org/protobuf/proto"
)

func ProtobufToJSON(message proto.Message) (string, error) {
    b, err := protojson.MarshalOptions{
        Indent: true,
        UseProtoNames: true,
        EmitUnpopulated: true,
    }
    return string(b), err
}

All 4 comments

There's a mismatch going on, since the code is trying to pass a "google.golang.org/protobuf/proto".Message to "github.com/golang/protobuf/jsonpb".Marshaler.MarshalToString, which expects a "github.com/golang/protobuf/proto".Message.

This can be resolved by either:

I recommend the first solution:

package serializer

import (
    "google.golang.org/protobuf/encoding/protojson"
    "google.golang.org/protobuf/proto"
)

func ProtobufToJSON(message proto.Message) (string, error) {
    b, err := protojson.MarshalOptions{
        Indent: true,
        UseProtoNames: true,
        EmitUnpopulated: true,
    }
    return string(b), err
}

Thanks a lot for quick turnaround.

Hi @dsnet Following up on this, I am still getting type mismatch. (happy to create a new issue if that helps)

My generated code has following imports

import (
    proto "github.com/golang/protobuf/proto"   // <---- can't edit this, this is generated
    protoreflect "google.golang.org/protobuf/reflect/protoreflect"
    protoimpl "google.golang.org/protobuf/runtime/protoimpl"
    reflect "reflect"
    sync "sync"
)

My serializer has

package serializer

import (
    "google.golang.org/protobuf/encoding/protojson"
    "google.golang.org/protobuf/proto"   // <----
)

func ProtobufToJSON(message proto.Message) (string, error) {
    b, err := protojson.Marshal(message)
    return string(b), err
}

The code was generated using protoc-gen-go

go install google.golang.org/protobuf/cmd/protoc-gen-go

The legacy import in _generated_ code causes a type mismatch when I try to serialize a generated model to JSON using ProtobufToJSON function above . What would be the right set of packages to import here?

Ah, looks like I had to call the ProtobufToJSON like this ProtobufToJSON(&message)

Was this page helpful?
0 / 5 - 0 ratings