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)
///////////////////////////////////////////////////////////////////////////////////////////
// 编码
data, err := proto.Marshal(&deviceInfo)
if err != nil {
log.Fatal("marshaling error: ", err)
}
fmt.Println(data)
// 调试输出
fmt.Println(proto.MarshalTextString(&deviceInfo))
// 解码
newDeviceInfo := &www_dllhook_com.DeviceInfo{}
err = proto.Unmarshal(data, newDeviceInfo)
if err != nil {
log.Fatal("unmarshaling error: ", err)
}
fmt.Println(newDeviceInfo)
// pb转json字符串
err = PB2JSON(newDeviceInfo, json_str)
fmt.Println(err)
fmt.Println(json_str)
}
syntax="proto2";
package www_dllhook_com;
message DeviceInfo {
optional string DeviceName = 1;
optional string DeviceType = 2;
optional string SystemVersion = 3;
}
发表评论