github.com/zhangdapeng520/zdpgo_json@v0.1.5/examples/jsonitor/main.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/zhangdapeng520/zdpgo_json/jsoniter"
     7  )
     8  
     9  type account struct {
    10  	Email    string  `json:"email"`
    11  	password string  `json:"password"` // 不会处理私有变量
    12  	Money    float64 `json:"money"`
    13  }
    14  
    15  type user struct {
    16  	Name    string
    17  	Age     int
    18  	Roles   []string
    19  	Skill   map[string]float64
    20  	Account account
    21  }
    22  
    23  func main() {
    24  	var json = jsoniter.ConfigCompatibleWithStandardLibrary
    25  
    26  	a := account{
    27  		Email:    "张大鹏",
    28  		password: "123456",
    29  		Money:    100.5,
    30  	}
    31  	u := user{
    32  		Name:    "张大鹏",
    33  		Age:     27,
    34  		Roles:   []string{"Owner", "Master"}, // 处理切片
    35  		Account: a,
    36  	}
    37  
    38  	// 序列化
    39  	jsonBytes, err := json.Marshal(u)
    40  	if err != nil {
    41  		panic(err)
    42  	}
    43  
    44  	// 反序列化
    45  	var u1 user
    46  	err = json.Unmarshal(jsonBytes, &u1)
    47  	if err != nil {
    48  		panic(err)
    49  	}
    50  
    51  	fmt.Println("成功:", u1, u1.Name, u1.Age, u1.Roles, u1.Account)
    52  }