golang里的json marshal && unmarshal

2021-01-17 20:11

阅读:388

标签:pack   ret   mit   def   var   Golan   ring   amp   efault   

package main

import (
	"encoding/json"
	"fmt"
)

type User struct {
	Name   string
	Age    int64
	Height float64
	Weight string  `json:"weight, default:helll"`
	Test   float64 `json:"test, omitempty"`
	Test2  float64 `json:"test2, default:10"`
	Test3  string  `json:"test3 default:sss"`
}

func main() {

	// Umarshal
	var str_json = []byte(`{"Name":"小花","Age":18,"Height":162}`)
	// json string--转-->struct
	var struct_user User
	err := json.Unmarshal(str_json, &struct_user)
	if err != nil {
		fmt.Printf("json.Unmarshal failed, err:%v\n", err)
		return
	}

	fmt.Printf("struct_user:%#v\n", struct_user)
	fmt.Printf("name:%#v\n", struct_user.Name)


	stu := User{}
	stu.Name = "test2"
	str1, _ := json.Marshal(stu)

	fmt.Printf("json: %s", str1)
}

golang里的json marshal && unmarshal

标签:pack   ret   mit   def   var   Golan   ring   amp   efault   

原文地址:https://www.cnblogs.com/muahao/p/13359974.html


评论


亲,登录后才可以留言!