基于这篇文章的最后一个代码进行验证。
https://blog.csdn.net/mijichui2153/article/details/133894403?csdn_share_tail=%7B%22type%22%3A%22blog%22%2C%22rType%22%3A%22article%22%2C%22rId%22%3A%22133894403%22%2C%22source%22%3A%22mijichui2153%22%7D
- github.com/golang/protobuf/jsonpb
- github.com/golang/protobuf/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;
}
注:json字段与pb字段严格对齐。
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":"[email protected]",
"FullName":"zhuoshuo"
}
`
fmt.Println("jsonStr is:", jsonStr)
p1 := &person.Person{}
jsonpb.UnmarshalString(jsonStr, p1)
fmt.Println("p1=", p1.String())
}
此时执行结果如下:
结论:json比proto多出来的字段不会被解析到pb,相当于不存在。
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":"[email protected]",
"FullName":"zhuoshuo",
"country":"china"
}
`
fmt.Println("jsonStr is:", jsonStr)
p1 := &person.Person{}
jsonpb.UnmarshalString(jsonStr, p1)
fmt.Println("p1=", p1.String())
}
在jsonStr中新增了school、country两个字段。执行结果如下:
结论:jsonStr中缺的字段转到pb后也缺少对应字段。
package main
import (
"fmt"
"json2pb/person"
"github.com/golang/protobuf/jsonpb"
)
func main() {
jsonStr := `
{
"id":"342224199110521627",
"country":"china",
"name":"shuozhuo",
"age":18,
"Email":"[email protected]",
"FullName":"zhuoshuo"
}
`
fmt.Println("jsonStr is:", jsonStr)
p1 := &person.Person{}
jsonpb.UnmarshalString(jsonStr, p1)
fmt.Println("p1=", p1.String())
}
在jsonStr中移除nickName、pen_name字段,执行结果如下:
和2.1是完全一样的。例如将jsonStr中的nickName改成nickName1,就会被当成一个全新字段。
结论:转pb时候,json中的字段名会尝试匹配proto字段名以及其后的json_name名。
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":"[email protected]",
"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,结果依然是能匹配过来的。