Golang序列化json

结构体转换为json

import (
	"encoding/json"
	"fmt"
)

type Student struct {
	Id     int
	Gender string
	Name   string
	Sno    string
}
s1 := Student{
		Id:     1,
		Gender: "男",
		Name:   "zs",
		Sno:    "s001",
	}
	jsonByte, _ := json.Marshal(s1)
	jsonStr := string(jsonByte)
	fmt.Print(jsonStr)

json转换为结构体

import (
	"encoding/json"
	"fmt"
)

type Student struct {
	Id     int
	Gender string
	Name   string
	Sno    string
}
var  str=`{"ID":1,"Gender":"男","Name":"zs","Sno":"s001"}`
	var s2 Student
	err := json.Unmarshal([]byte(str), &s2)
	if err != nil {
		fmt.Print(err)
	}
fmt.Printf("%#v", s2)

结构体tag标签

import (
	"encoding/json"
	"fmt"
)

type Student struct {
	Id     int    `json:"id"` //tag序列化
	Gender string `json:"gender"`
	Name   string `json:"name"`
	Sno    string `json:"sno"`
}
s1 := Student{
		Id:     1,
		Gender: "男",
		Name:   "zs",
		Sno:    "s001",
	}
	jsonByte, _ := json.Marshal(s1)
	jsonStr := string(jsonByte)
	fmt.Print(jsonStr)
	//{"id":1,"gender":"男","name":"zs","sno":"s001"}

Golang序列化json
http://www.jcwit.com/article/6/
作者
Carlos
发布于
2024年3月8日
许可协议