proto与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)
  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值