63 lines
1.6 KiB
Go
63 lines
1.6 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
fmt "fmt"
|
|
)
|
|
|
|
// BaseModel 公共基础模型
|
|
type BaseModel struct {
|
|
ID int64 `json:"id,string,omitempty"`
|
|
CreatedAt string `json:"created_at,omitempty"`
|
|
}
|
|
|
|
// Order 订单模型(全标签演示)
|
|
type Order struct {
|
|
BaseModel `json:",inline"`
|
|
OrderNo string `json:"order_no"`
|
|
Status int `json:"status,omitempty"`
|
|
Phone int64 `json:"phone,string,omitempty"`
|
|
Password string `json:"-"`
|
|
Extra struct {
|
|
Level int `json:"level"`
|
|
} `json:",nosquash"`
|
|
Ignore string `json:",allowunknown"`
|
|
}
|
|
|
|
func main() {
|
|
order := Order{
|
|
BaseModel: BaseModel{ID: 202606001, CreatedAt: "2026-06-02"},
|
|
OrderNo: "BULMA-ORDER-001",
|
|
Password: "secret_123",
|
|
}
|
|
data, _ := json.MarshalIndent(order, "", " ")
|
|
fmt.Println("\n=== 高级标签运行结果 ===")
|
|
fmt.Println(string(data))
|
|
|
|
// 演示 allowunknown 的反序列化功能
|
|
fmt.Println("\n=== 反序列化测试(含未知字段)===")
|
|
jsonWithUnknown := `{
|
|
"id": "202606002",
|
|
"created_at": "2026-06-02",
|
|
"order_no": "BULMA-ORDER-002",
|
|
"unknown_field": "test",
|
|
"extra_field": 123
|
|
}`
|
|
var newOrder Order
|
|
err := json.Unmarshal([]byte(jsonWithUnknown), &newOrder)
|
|
if err != nil {
|
|
fmt.Printf("反序列化失败:%v\n", err)
|
|
} else {
|
|
fmt.Printf("成功解析:%+v\n", newOrder)
|
|
}
|
|
|
|
// 演示 omitempty 的效果
|
|
fmt.Println("\n=== omitempty 效果对比 ===")
|
|
emptyOrder := Order{
|
|
BaseModel: BaseModel{ID: 0}, // ID 为 0,会被 omit
|
|
OrderNo: "BULMA-ORDER-003",
|
|
}
|
|
data2, _ := json.MarshalIndent(emptyOrder, "", " ")
|
|
fmt.Println(string(data2))
|
|
}
|