GolangNote

Golang笔记

把JSON 字符串转为go struct 的两种方式

Permalink

把一个 JSON 字符串转为一个 go struct 有两种方式:

用 json.Unmarshal

Go: json.Unmarshal
1
2
3
4
data, err := ioutil.ReadAll(resp.Body)
if err == nil && data != nil {
    err = json.Unmarshal(data, value)
}

用 json.NewDecoder.Decode

Go: json.NewDecoder.Decode
1
err = json.NewDecoder(resp.Body).Decode(value)

选择那种方式,取决于自己的字符串来源:

  • 当来自 io.Reader stream 时就选用 json.Decoder
  • JSON 数据本来就在内存里,就选用 json.Unmarshal

下面是两种方式的使用示例:

Go: json to struct
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package main

import (
    "encoding/json"
    "fmt"
    "strings"
)

func main() {
    const jsonStream = `{"Name": "Ed", "Text": "Knock knock."}`

    type Message struct {
        Name, Text string
    }

    var m Message

    // 用json.NewDecoder
    dec := json.NewDecoder(strings.NewReader(jsonStream))
    dec.Decode(&m)
    fmt.Printf("%s: %s\n", m.Name, m.Text)

    // 用 json.Unmarshal
    json.Unmarshal([]byte(jsonStream), &m)
    fmt.Printf("%s: %s\n", m.Name, m.Text)

    fmt.Println("done")
}

运行输出:

Bash: json to struct 输出
1
2
3
Ed: Knock knock.
Ed: Knock knock.
done

本文网址: https://golangnote.com/topic/82.html 转摘请注明来源

Related articles

Write a Comment to "把JSON 字符串转为go struct 的两种方式"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 2ms