标签 - GO
- package main
-
- import (
- "github.com/golang/protobuf/proto"
- "git.dllhook.com/protobuf_test/proto"
- "log"
- "fmt"
- "encoding/json"
- )
-
- func JSON2PB(form_json_str string, to_pb proto.Message) error {
- // json字符串转pb
- return json.Unmarshal([]byte(form_json_str), &to_pb)
- }
-
- func PB2JSON(from_pb proto.Message, to_json_str string) error {
- // pb转json字符串
- json_str, err := json.Marshal(from_pb)
- if err == nil {
- to_json_str = string(json_str)
- }
-
- return err
- }
-
- func main() {
- ///////////////////////////////////////////////////////////////////////////////////////////
- /* -- 直接对pb赋值
- deviceInfo := example.DeviceInfo{
- DeviceName: proto.String("PiaoYun iPhone"),
- DeviceType: proto.String("iPhone"),
- SystemVersion: proto.String("9.0.2"),
- }
- */
-
- // json转pb
- json_str := `{"DeviceName":"PiaoYun iPhone","DeviceType":"iPhone","SystemVersion":"9.0.2"}`
- var deviceInfo www_dllhook_com.DeviceInfo
- err := JSON2PB(json_str, &deviceInfo)
- fmt.Println(err)
- /////////////////////