Golang Json 编解码

编码

Go 复制代码
json.NewEncoder(<Writer>).encode(v)
json.Marshal(&v)

解码

Go 复制代码
json.NewDecoder(<Reader>).decode(&v)
json.Unmarshal([]byte, &v)

使用示例

Go 复制代码
type Person struct {
    Name string `json:"name"`
    Age int `json:"age"`
}
Go 复制代码
func main()  {
    // 1. 使用 json.Marshal 编码
    person1 := Person{"张三", 24}
    bytes1, err := json.Marshal(&person1)
    if err == nil {
        // 返回的是字节数组 []byte
        fmt.Println("json.Marshal 编码结果: ", string(bytes1))
    }


    // 2. 使用 json.Unmarshal 解码
    str := `{"name":"李四","age":25}`
    // json.Unmarshal 需要字节数组参数, 需要把字符串转为 []byte 类型
    bytes2 := []byte(str) // 字符串转换为字节数组
    var person2 Person    // 用来接收解码后的结果
    if json.Unmarshal(bytes2, &person2) == nil {
        fmt.Println("json.Unmarshal 解码结果: ", person2.Name, person2.Age)
    }


    // 3. 使用 json.NewEncoder 编码
    person3 := Person{"王五", 30}
    // 编码结果暂存到 buffer
    bytes3 := new(bytes.Buffer)
    _ = json.NewEncoder(bytes3).Encode(person3)
    if err == nil {
        fmt.Print("json.NewEncoder 编码结果: ", string(bytes3.Bytes()))
    }


    // 4. 使用 json.NewDecoder 解码
    str4 := `{"name":"赵六","age":28}`
    var person4 Person
    // 创建一个 string reader 作为参数
    err = json.NewDecoder(strings.NewReader(str4)).Decode(&person4)
    if err == nil {
        fmt.Println("json.NewDecoder 解码结果: ", person4.Name, person4.Age)
    }

未知类型处理

使用 interface 接收 json.Unmarshal 的结果,然后利用 type assertion 特性 (把解码结果转换为 mapstringinterface{} 类型) 来进行后续操作。

Go 复制代码
func main() {
    b := []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`)


    var f interface{}
    json.Unmarshal(b, &f)


    m := f.(map[string]interface{})
    fmt.Println(m["Parents"])  // 读取 json 内容
    fmt.Println(m["a"] == nil) // 判断键是否存在
}

marshal和NewDecoder区别

1、json.NewDecoder是从一个流里面直接进行解码,代码精干

2、json.Unmarshal是从已存在与内存中的json进行解码

3、相对于解码,json.NewEncoder进行大JSON的编码比json.marshal性能高,因为内部使用pool

场景应用

1、json.NewDecoder用于http连接与socket连接的读取与写入,或者文件读取

2、json.Unmarshal用于直接是byte的输入

Go 复制代码
func HandleUse(w http.ResponseWriter, r *http.Request) {
    var u Use
    if err := json.NewDecoder(r.Body).Decode(&u); err != nil {
        w.WriteHeader(http.StatusInternalServerError)
        return
    }
    w.WriteHeader(http.StatusOK)
    fmt.Fprintf(w, "姓名:%s,年龄:%d", u.Name, u.Age)
}

将Json数据转换为map切片

Go 复制代码
//将json数据转换为map切片
func maina6(){
    jsonStr := `[{"age":21,"hobby":["打"],"name":"liyi","sex":true},{"name":"linging"},{"age":18,"hobby":["学习"],"name":"yiyi","sex":true}]`
    jsonBytes := []byte(jsonStr)
    dataSlice := make([]map[string]interface{},0)
    err := json.Unmarshal(jsonBytes,&dataSlice)
    if err != nil {
        fmt.Println("反序列化失败,err=",err)
    }
    fmt.Println(dataSlice)
}
相关推荐
Ycocol16 小时前
AS同一个目录下的类导入导入其他类爆红无法跳转但是可以编译
android·ide·android studio
AI行业学习17 小时前
CC‑Switch v3.16.1 免费下载(Windows+macOS+Linux)、使用方法【2026.6.11】
linux·开发语言·windows·python·macos·前端框架·html
一个人旅程~18 小时前
如何进行win11右键菜单优化(poweshell命令行与bat自动脚本方式)
windows·经验分享·macos·电脑
坏小虎18 小时前
macOS 安装 Ghostty 终端完整教程:环境、依赖与美化配置
macos·策略模式
麦麦麦当劳大王18 小时前
OpenClaw安装部署(Windows/Linux/MacOS)
linux·windows·macos
会Tk矩阵群控的小木19 小时前
独立站tk矩阵系统站外引流实战:多账号管理+风控+数据分析代码实现
运维·macos·自动化·个人开发·tk矩阵
console.log('npc')19 小时前
FigmaEX 汉化,免费使用,下载与安装指南(Windows/Mac)
windows·macos·ui·figma
云水-禅心19 小时前
解决MacOS 安装Python之后默认版本指向不正确问题
开发语言·python·macos
Mars-xq20 小时前
vscode 开发Android
android·ide·vscode
Rudon滨海渔村20 小时前
macOS文件夹创建桌面快捷方式 - 发送到桌面快捷方式
macos