ZBLOG

golang json字符串转protobuf message

在 golang 中,我们可以使用 jsonpb 包将 JSON 字符串转换为 protobuf message。

首先,我们需要定义一个 protobuf message,并生成对应的 go 文件。假设我们的 protobuf 文件名为 person.proto,其中包含如下定义:

  1. syntax = "proto3";
  2. message Person {
  3. string name = 1;
  4. int32 age = 2;
  5. }

然后,我们就可以使用 jsonpb.UnmarshalString 函数将 JSON 字符串转换为 Person 类型的 protobuf message。示例代码如下:

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/golang/protobuf/jsonpb"
  5. "github.com/golang/protobuf/proto"
  6. )
  7. func main() {
  8. jsonString := `{"name": "Tom", "age": 25}`
  9. person := &Person{}
  10. if err := jsonpb.UnmarshalString(jsonString, person); err != nil {
  11. fmt.Println("Failed to unmarshal json:", err)
  12. return
  13. }
  14. fmt.Printf("Name: %s, Age: %d\n", person.GetName(), person.GetAge())
  15. }

输出:

  1. Name: Tom, Age: 25

注意,在使用 jsonpb.UnmarshalString 函数之前,我们需要先创建一个空的 Person 类型的 protobuf message。这里我们使用 &Person{} 来创建一个空的 Person 类型对象。如果出现解析错误,函数会返回非空的错误对象。

另外,我们需要在代码中添加如下两行导入语句:

  1. import "github.com/golang/protobuf/jsonpb"
  2. import "github.com/golang/protobuf/proto"

其中第一行是导入 jsonpb 包,用于将 JSON 字符串转换为 protobuf message;第二行是导入 proto 包,用于操作 protobuf message。

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=2022

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?