标签 - GO

GO Protobuf    2019-08-26 14:12:37    148    0    0
  1. package main
  2.  
  3. import (
  4.    "github.com/golang/protobuf/proto"
  5.    "git.dllhook.com/protobuf_test/proto"
  6.    "log"
  7.    "fmt"
  8.    "encoding/json"
  9. )
  10.  
  11. func JSON2PB(form_json_str string, to_pb proto.Message) error {
  12.    // json字符串转pb
  13.    return json.Unmarshal([]byte(form_json_str), &to_pb)
  14. }
  15.  
  16. func PB2JSON(from_pb proto.Message, to_json_str string) error {
  17.    // pb转json字符串
  18.    json_str, err := json.Marshal(from_pb)
  19.    if err == nil {
  20.       to_json_str = string(json_str)
  21.    }
  22.  
  23.    return err
  24. }
  25.  
  26. func main() {
  27.    ///////////////////////////////////////////////////////////////////////////////////////////
  28.    /* -- 直接对pb赋值
  29.    deviceInfo := example.DeviceInfo{
  30.       DeviceName: proto.String("PiaoYun iPhone"),
  31.       DeviceType: proto.String("iPhone"),
  32.       SystemVersion: proto.String("9.0.2"),
  33.    }
  34.    */
  35.  
  36.    // json转pb
  37.    json_str := `{"DeviceName":"PiaoYun iPhone","DeviceType":"iPhone","SystemVersion":"9.0.2"}`
  38.    var deviceInfo www_dllhook_com.DeviceInfo
  39.    err := JSON2PB(json_str, &deviceInfo)
  40.    fmt.Println(err)
  41.    /////////////////////