golang json 使用了omitempty
注解应该使用指针定义数据,否则序列化 int的0值,string的"" 会和理解的有偏差,注意下面两图输出结果的区别
id和order输出正常
id为0 order为""没有json字符串中没有输出
package main
import (
"encoding/json"
"fmt"
)
var jsonBlob = []byte(`[
{"Name": "c++", "Order": "1","id":0},
{"Name": "lua", "Order": ""},
{"Name": "golang"}
]`)
type Book struct {
Name string `json:"name"`
Order string `json:"order,omitempty"`
ID int `json:"id,omitempty"`
}
func main() {
var books []Book
err := json.Unmarshal(jsonBlob, &books)
if err != nil {
fmt.Println("error:", err)
}
fmt.Printf("%+v \n", books)
data, err := json.Marshal(books)
if err != nil {
fmt.Printf(err.Error())
return
}
fmt.Printf("data:%v \n", string(data))
}
###参考
https://blog.csdn.net/xk18791196562/article/details/85328749
http://static.markbest.site/blog/71.html