把对象解析为字符串(Marshal)

type Pet struct {
	Name  string `json:"petName"`          //在字符串里面键名为petName
	Sex   string `json:"petSex,omitempty"` //在字符串里面键名为petSex,如果空,则出现在字符串里
	Owner []Person
}

type Person struct {
	Name string
	Sex  string `json:"-"` //不会出现在字符串里
	Age  int    `json:",omitempty"` //如果为空,则不会出现在字符串里,注意前面的逗号
}

//把对象转换为字符串
func GetStringFromObject() {
	p := Pet{
		Name: "puff",
		Owner: [] Person{
			{Name: "alex", Sex: "male"},
			{Name: "alice", Sex: "female"},
		},
	}
	b, err := json.Marshal(&p)
	if err != nil {
		panic(err)
	}

	jsonStr := string(b)
	fmt.Println(jsonStr)
}

字符串解析为对象(Unmarshal)

func GetObjectFromString() {
	jsonStr := `{"key":"value","friends":[{"name":"alex","age":25},{"name":"alice","age":32}]}`
	result := make(map[string]interface{})
	if err := json.Unmarshal([]byte(jsonStr), &result); err != nil {
		panic(err)
	}
	fmt.Println(result)
}

io.Reader解析为对象

//把io.reader解析为对象
func GetObjectFromHttp() {

	bodyWriter := new(bytes.Buffer)

	resp, err := http.Post("https://finance-api.fengkongcloud.com/v3/finance/lending", "application/json", bodyWriter)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	result := make(map[string]interface{})
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		panic(err)
	}

	fmt.Println(result)
}