proto与json的互相转换
- proto使用
- proto
- python dict和message
- python message序列化
- golang
- message序列化
- message转json
proto使用
生成逻辑请参考
https://blog.csdn.net/qq_43645782/article/details/127112663
proto
syntax = "proto3";
message testRequest {
string id = 1;
}
python dict和message
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'>
python message序列化
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
在golang使用比较简单,protobuf生成的go struct是支持proto和json的序列化和反序列化的
golang对于proto的序列化与反序列化同样需要使用专用库来实现,效果比较好
"google.golang.org/protobuf/encoding/protojson"
proto在初始化的时候已经将message的信息保存到内存内
proto进行反序列化时,在遍历到每一个json key时,会尝试在内存中查找key是否可以对应上,会分别查询proto的name与json name
代码可以参考
https://github.com/protocolbuffers/protobuf-go/blob/master/encoding/protojson/decode.go#L175
message序列化
out, err := proto.Marshal(protoObj)
err := proto.Unmarshal(in, &protoObj)
message转json
out, err := protojson.Marshal(protoObj)
err := protojson.Unmarshal(in, &protoObj)