基于这篇文章的最后一个代码进行验证。
1、准备
(1)依赖的第三方库
(2)创建person.proto文件
syntax = "proto3";
package person;
message Person {
string id = 1 [json_name = "myid"];
string nickName = 2;
string pen_name = 3;
string name = 4;
int32 age = 5 [json_name = "myage"];
string Email = 6;
string FullName = 7;
}
(3)构建可执行文件myperson.go
注:json字段与pb字段严格对齐。
Go
package main
import (
"fmt"
"json2pb/person"
"github.com/golang/protobuf/jsonpb"
)
func main() {
jsonStr := `
{
"id":"342224199110521627",
"nickName":"bangbang",
"pen_name":"luxun",
"name":"shuozhuo",
"age":18,
"Email":"2300659533@qq.com",
"FullName":"zhuoshuo"
}
`
fmt.Println("jsonStr is:", jsonStr)
p1 := &person.Person{}
jsonpb.UnmarshalString(jsonStr, p1)
fmt.Println("p1=", p1.String())
}
此时执行结果如下:
2、验证各关注点
2.1、proto定义不变json中多了若干字段会如何?
结论:json比proto多出来的字段不会被解析到pb,相当于不存在。
Go
package main
import (
"fmt"
"json2pb/person"
"github.com/golang/protobuf/jsonpb"
)
func main() {
jsonStr := `
{
"id":"342224199110521627",
"nickName":"bangbang",
"school":"ZJU",
"pen_name":"luxun",
"name":"shuozhuo",
"age":18,
"Email":"2300659533@qq.com",
"FullName":"zhuoshuo",
"country":"china"
}
`
fmt.Println("jsonStr is:", jsonStr)
p1 := &person.Person{}
jsonpb.UnmarshalString(jsonStr, p1)
fmt.Println("p1=", p1.String())
}
在jsonStr中新增了school、country两个字段。执行结果如下:
2.2、proto定义不变json中少了若干字段会如何?
结论:jsonStr中缺的字段转到pb后也缺少对应字段。
Go
package main
import (
"fmt"
"json2pb/person"
"github.com/golang/protobuf/jsonpb"
)
func main() {
jsonStr := `
{
"id":"342224199110521627",
"country":"china",
"name":"shuozhuo",
"age":18,
"Email":"2300659533@qq.com",
"FullName":"zhuoshuo"
}
`
fmt.Println("jsonStr is:", jsonStr)
p1 := &person.Person{}
jsonpb.UnmarshalString(jsonStr, p1)
fmt.Println("p1=", p1.String())
}
在jsonStr中移除nickName、pen_name字段,执行结果如下:
2.3、json有pb不存在的字段会如何?
和2.1是完全一样的。例如将jsonStr中的nickName改成nickName1,就会被当成一个全新字段。
2.4、pb中定义的json_name是否生效?
结论:转pb时候,json中的字段名会尝试匹配proto字段名以及其后的json_name名。
Go
package main
import (
"fmt"
"json2pb/person"
"github.com/golang/protobuf/jsonpb"
)
func main() {
jsonStr := `
{
"myid":"342224199110521627",
"nickName":"bangbang",
"pen_name":"luxun",
"name":"shuozhuo",
"myage":18,
"Email":"2300659533@qq.com",
"FullName":"zhuoshuo"
}
`
fmt.Println("jsonStr is:", jsonStr)
p1 := &person.Person{}
jsonpb.UnmarshalString(jsonStr, p1)
fmt.Println("p1=", p1.String())
}
如图将jsonStr中的id字段改成proto中id字段的别名myid、age改成myage,结果依然是能匹配过来的。