golang-json基礎使用

golang中直接導入“encoding/json”包即可使用json.

普通結構體的序列化與反序列化

主要是json.Marshal與json.Unmarshal兩個函數的使用。

func Marshal(v interface{}) ([]byte, error)
func Unmarshal(data []byte, v interface{}) error

這裏示例代碼及輸出爲:

package main

import (
	"fmt"
	"encoding/json"
)

type Student struct {
	Name   string
	Age    int64
	Weight float64
	Height float64
}

func main() {

	s1 := Student{
		Name:   "jack",
		Age:    20,
		Weight: 71.5,
		Height: 172.5,
	}

	b, err := json.Marshal(s1)
	if err != nil {
		fmt.Printf("json.Marshal failed, err:%v\n", err)
		return
	}
	fmt.Printf("s1: %s\n", b)

	var s2 Student
	err = json.Unmarshal(b, &s2)
	if err != nil {
		fmt.Printf("json.Unmarshal failed, err:%v\n", err)
		return
	}
	fmt.Printf("s2: %#v\n", s2)
}

輸出:

s1: {"Name":"jack","Age":20,"Weight":71.5,"Height":172.5}
s2: main.Student{Name:"jack", Age:20, Weight:71.5, Height:172.5}

具名嵌套結構體的序列化與反序列化

延用以上的代碼,將普通結構體改爲具名嵌套結構體:

type BodyInfo struct {
	Weight float64
	Height float64
}

type Student struct {
	Name   string
	Age    int64
	BodyInfo BodyInfo
}

此時s1有不同的初始化方法:
初始化一:

	s1 := Student{
		Name:   "jack",
		Age:    20,
		BodyInfo: BodyInfo{
			Weight: 71.5,
		    Height: 172.5,
		},
	}

輸出:

s1: {"Name":"jack","Age":20,"BodyInfo":{"Weight":71.5,"Height":172.5}}
s2: main.Student{Name:"jack", Age:20, BodyInfo:main.BodyInfo{Weight:71.5, Height:172.5}}

初始化二:

	var s1 Student
	s1.Name = "jack"
	s1.Age = 20
	s1.BodyInfo = BodyInfo {
		Weight: 71.5,
		Height: 172.5,
	}

輸出:

s1: {"Name":"jack","Age":20,"BodyInfo":{"Weight":71.5,"Height":172.5}}
s2: main.Student{Name:"jack", Age:20, BodyInfo:main.BodyInfo{Weight:71.5, Height:172.5}}

匿名嵌套結構體的序列化與反序列化

延用以上的代碼,將普通結構體改爲匿名嵌套結構體:

type BodyInfo struct {
	Weight float64
	Height float64
}

type Student struct {
	Name   string
	Age    int64
	BodyInfo
}

此時s1有不同的初始化方法:
初始化一:

    var s1 Student
	s1.Name = "jack"
	s1.Age = 20
	s1.BodyInfo = BodyInfo {
		Weight: 71.5,
		Height: 172.5,
	}

輸出:

s1: {"Name":"jack","Age":20,"Weight":71.5,"Height":172.5}
s2: main.Student{Name:"jack", Age:20, BodyInfo:main.BodyInfo{Weight:71.5, Height:172.5}}

初始化二:

s1 := Student{
		Name:   "jack",
		Age:    20,
		BodyInfo: BodyInfo{
			Weight: 71.5,
			Height: 172.5,
		},
	}

輸出:

str:{"Name":"jack","Age":20,"Weight":71.5,"Height":172.5}
s2:main.Student{Name:"jack", Age:20, BodyInfo:main.BodyInfo{Weight:71.5, Height:172.5}}

注:具名嵌套結構體與匿名嵌套結構體在序列化後存在是否攤平的差別。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章