生成逻辑请参考
https://blog.csdn.net/qq_43645782/article/details/127112663
syntax = "proto3";
message testRequest {
string id = 1;
}
import json
from google.protobuf.json_format import MessageToJson, MessageToDict
from google.protobuf.json_format import ParseDict, Parse
from grpc0.code.test_pb2 import testRequest
if __name__ == '__main__':
proto_obj = testRequest(
id="123",
)
print(f"{MessageToDict(proto_obj)=}")
print(f"{MessageToJson(proto_obj)=}")
json_obj = {"id": "456"}
print(f"{Parse(json.dumps(json_obj), testRequest)=}")
print(f"{ParseDict(json_obj, testRequest)=}")
MessageToDict(proto_obj)={'id': '123'}
MessageToJson(proto_obj)='{\n "id": "123"\n}'
Parse(json.dumps(json_obj), testRequest)=<class 'test_pb2.testRequest'>
ParseDict(json_obj, testRequest)=<class 'test_pb2.testRequest'>
import json
from google.protobuf.json_format import MessageToJson, MessageToDict
from google.protobuf.json_format import ParseDict, Parse
from grpc0.code.test_pb2 import testRequest
if __name__ == '__main__':
proto_obj = testRequest(
id="123",
)
proto_bytes = proto_obj.SerializeToString()
print(proto_bytes)
proto_obj1 = testRequest()
proto_obj1.ParseFromString(proto_bytes)
print(proto_obj)
print(proto_obj1)
b'\n\x03123'
id: "123"
id: "123"
在golang使用比较简单,protobuf生成的go struct是支持proto和json的序列化和反序列化的
out, err := proto.Marshal(protoObj)
err := proto.Unmarshal(in, &protoObj)
out, err := json.Marshal(protoObj)
err := json.Unmarshal(in, &protoObj)