ToB企服应用市场:ToB评测及商务社交产业平台

标题: protolator - Protobuf <==> json [打印本页]

作者: 徐锦洪    时间: 2023-7-31 12:50
标题: protolator - Protobuf <==> json
github.com/hyperledger/fabric-config/protolator 是 Hyperledger Fabric 中的一个 Go 包,用于将 Protocol Buffers(ProtoBuf)消息和 JSON 格式之间进行转换。它提供了一种方便的方式来将 Fabric 配置文件(以 ProtoBuf 格式表示)与 JSON 配置文件之间进行相互转换。这对于 Fabric 的配置管理和部署非常有用,使得用户可以轻松地在不同的配置格式之间进行切换。
功能和用法

protolator 提供了一组功能,用于在 ProtoBuf 格式和 JSON 格式之间进行转换:
DeepMarshalJSON

func DeepMarshalJSON(m proto.Message) ([]byte, error)
DeepUnmarshalJSON

func DeepUnmarshalJSON(data []byte, m proto.Message) error
Nested

type Nested struct{...}
使用示例
  1. package main
  2. import (
  3.         "fmt"
  4.         "github.com/golang/protobuf/proto"
  5.         "github.com/hyperledger/fabric-config/protolator"
  6.         "encoding/json"
  7. )
  8. // 使用 proto 文件定义的 message 结构
  9. // 假设定义了 proto 文件如下:
  10. // message MyData {
  11. //     string name = 1;
  12. //     int32 age = 2;
  13. // }
  14. type MyData struct {
  15.         Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
  16.         Age  int32  `protobuf:"varint,2,opt,name=age" json:"age,omitempty"`
  17. }
  18. func main() {
  19.         // 创建一个 MyData 实例
  20.         data := &MyData{
  21.                 Name: "John",
  22.                 Age:  30,
  23.         }
  24.         // 使用 DeepMarshalJSON 将 ProtoBuf 数据转换为 JSON 字节流
  25.         jsonData, err := protolator.DeepMarshalJSON(data)
  26.         if err != nil {
  27.                 fmt.Println("Error marshaling to JSON:", err)
  28.                 return
  29.         }
  30.         // 使用 DeepUnmarshalJSON 将 JSON 字节流转换为 ProtoBuf 数据
  31.         newData := &MyData{}
  32.         err = protolator.DeepUnmarshalJSON(jsonData, newData)
  33.         if err != nil {
  34.                 fmt.Println("Error unmarshaling from JSON:", err)
  35.                 return
  36.         }
  37.         // 输出结果
  38.         fmt.Println("Original data:", data)
  39.         fmt.Println("JSON data:", string(jsonData))
  40.         fmt.Println("Unmarshaled data:", newData)
  41. }
复制代码
在上述示例中,我们使用 github.com/hyperledger/fabric-config/protolator 的 DeepMarshalJSON 方法将 MyData 结构体从 ProtoBuf 格式转换为 JSON 格式的字节流,并使用 DeepUnmarshalJSON 方法将 JSON 字节流再转换回 ProtoBuf 格式的数据。输出结果显示了原始数据、转换后的 JSON 数据以及再次转换回来后的数据。
  
声明:本作品采用署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)进行许可,使用时请注明出处。
Author: mengbin
blog: mengbin
Github: mengbin92
cnblogs: 恋水无意

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4