转化为json格式
func Marshal(v interface{}) ([]byte, error) //将v(一般为结构体)转化为json格式
// json.go package main import ( "encoding/json" "fmt" "log" "os" ) type Address struct { Type string City string Country string } type VCard struct { FirstName string LastName string Addresses []*Address Remark string } func main() { pa := &Address{"private", "Aartselaar", "Belgium"} wa := &Address{"work", "Boom", "Belgium"} vc := VCard{"Jan", "Kersschot", []*Address{pa, wa}, "none"} // fmt.Printf("%v: \n", vc) // {Jan Kersschot [0x126d2b80 0x126d2be0] none}: // JSON format: js, _ := json.Marshal(vc) fmt.Printf("JSON format: %s", js) }
结果:
{"FirstName":"Jan","LastName":"Kersschot","Addresses":[{"Type":"private","City":
"Aartselaar","Country":"Belgium"},{"Type":"work","City":"Boom","Country":"Belgiu
m"}],"Remark":"none"}
func MarshalIndent(v any, prefix string, indent string) ([]byte, error)
Code:
data := map[string]int{ "a": 1, "b": 2, } b, err := json.MarshalIndent(data, "<prefix>", "<indent>") if err != nil { log.Fatal(err) } fmt.Println(string(b))
Output:
{
<prefix><indent>"a": 1,
<prefix><indent>"b": 2
<prefix>}
func main() { pa := &Address{"private", "Aartselaar", "Belgium"} wa := &Address{"work", "Boom", "Belgium"} vc := VCard{"Jan", "Kersschot", []*Address{pa, wa}, "none"} // fmt.Printf("%v: \n", vc) // {Jan Kersschot [0x126d2b80 0x126d2be0] none}: // JSON format: js, _ := json.MarshalIndent(vc, " ", " ") fmt.Printf("JSON format: %s", js) }
结果:
{
"FirstName": "Jan",
"LastName": "Kersschot",
"Addresses": [
{
"Type": "private",
"City": "Aartselaar",
"Country": "Belgium"
},
{
"Type": "work",
"City": "Boom",
"Country": "Belgium"
}
],
"Remark": "none"
}
反序列化
func Unmarshal(data []byte, v interface{}) //error 把 JSON 解码为数据结构。
func main() { pa := &Address{"private", "Aartselaar", "Belgium"} wa := &Address{"work", "Boom", "Belgium"} vc := VCard{"Jan", "Kersschot", []*Address{pa, wa}, "none"} js, _ := json.MarshalIndent(vc, " ", " ") fmt.Printf("%s\n", js) var _vc VCard json.Unmarshal(js, &_vc) fmt.Println(_vc.FirstName, _vc.LastName, _vc.Addresses[0], _vc.Addresses[1], _vc.Remark) }
结果:
{
"FirstName": "Jan",
"LastName": "Kersschot",
"Addresses": [
{
"Type": "private",
"City": "Aartselaar",
"Country": "Belgium"
},
{
"Type": "work",
"City": "Boom",
"Country": "Belgium"
}
],
"Remark": "none"
}
Jan Kersschot &{private Aartselaar Belgium} &{work Boom Belgium} none
解码任意的数据:
json 包使用 map[string]interface{}
和 []interface{}
储存任意的 JSON 对象和数组;其可以被反序列化为任何的 JSON blob 存储到接口值中。
例子:
b := []byte(`{"Name": "Wednesday", "Age": 6, "Parents": ["Gomez", "Morticia"]}`)
var f interface{}
err := json.Unmarshal(b, &f)
//f指向的是一个mpakey 是一个字符串,value 是自身存储作为空接口类型的值:
map[string]interface{} {
"Name": "Wednesday",
"Age": 6,
"Parents": []interface{} {
"Gomez",
"Morticia",
},
}
使用类型断言:
m := f.(map[string]interface{})
可以通过 for range 语法和 type switch 来访问其实际类型:
for k, v := range m {
switch vv := v.(type) {
case string:
fmt.Println(k, "is string", vv)
case int:
fmt.Println(k, "is int", vv)
case []interface{}:
fmt.Println(k, "is an array:")
for i, u := range vv {
fmt.Println(i, u)
}
default:
fmt.Println(k, "is of a type I don’t know how to handle")
}
}
解码数据到结构
如果我们事先知道 JSON 数据,我们可以定义一个适当的结构并对 JSON 数据反序列化:
type FamilyMember struct { Name string Age int Parents []string } var m FamilyMember err := json.Unmarshal(b, &m)
编码和解码流
json
包提供 Decoder
和 Encoder
类型来支持常用 JSON 数据流读写。NewDecoder()
和 NewEncoder()
函数分别封装了 io.Reader
和 io.Writer
接口。
func NewDecoder(r io.Reader) *Decoder func NewEncoder(w io.Writer) *Encoder
要想把 JSON 直接写入文件,可以使用 json.NewEncoder
初始化文件(或者任何实现 io.Writer
的类型),并调用 Encode()
;反过来与其对应的是使用 json.NewDecoder
和 Decode()
函数:
func NewDecoder(r io.Reader) *Decoder func (dec *Decoder) Decode(v interface{}) error
func main() { pa := &Address{"private", "Aartselaar", "Belgium"} wa := &Address{"work", "Boom", "Belgium"} vc := VCard{"Jan", "Kersschot", []*Address{pa, wa}, "none"} j, _ := os.OpenFile("json.txt", os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0666) j_encoder := json.NewEncoder(j) j_encoder.Encode(vc) defer j.Close() }
func main() { var vc VCard j, _ := os.Open("./json.txt") defer j.Close() j_Decoder := json.NewDecoder(j) j_Decoder.Decode(&vc) fmt.Println(vc.FirstName, vc.LastName, vc.Addresses[0], vc.Addresses[1], vc.Remark) }
标签:vc,string,fmt,Belgium,json,Address,go From: https://www.cnblogs.com/dadishi/p/17060851.html