Loading

详解 golang 中Json的解码和编码

1.Json编码

参考文档:文档链接

2.Json解码

代码示例:

package main

import (
	"encoding/json"
	"fmt"
)

func main()  {
	// json -> unmarshal
	raw := `{"one": 2}`
	var dst map[string]int
	_ = json.Unmarshal([]byte(raw), &dst)
	fmt.Printf("after unmarshal, dst data: %v, type: %T\n", dst, dst)

	// marshal -> json
	src := map[string]string{"one": "one"}
	dstByte, _ := json.Marshal(src)
	srcJson := string(dstByte)
	fmt.Printf("src->json: %v, type: %T", srcJson, srcJson)
}

运行结果:

after unmarshal, dst data: map[one:2], type: map[string]int
src->json: {"one":"one"}, type: string

posted @ 2023-02-13 10:31  Carver大脸猫  阅读(43)  评论(0)    收藏  举报