例如:我们把上面例子中 value 类型由 int 修改为 string 后再次运行代码,你将得到 Unmarshal error is: json: cannot unmarshal number into Go value of type string 的错误提醒。
数据对应关系
JSON 和 Go 数据类型对照表:
类型
JSON
Go
bool
true, false
true, false
string
"a"
string("a")
整数
1
int(1), int32(1), int64(1) ...
浮点数
3.14
float32(3.14), float64(3.14) ...
数组
[1,2]
[2]int{1,2}, []int{1, 2}
对象 Object
{"a": "b"}
map[string]string, struct
未知类型
...
interface{}
例如:
package main
import (
"encoding/json"
"fmt"
)
func main() {
var (
d1 = `false`
v1 bool
)
json.Unmarshal([]byte(d1), &v1)
printHelper("d1", v1)
var (
d2 = `2`
v2 int
)
json.Unmarshal([]byte(d2), &v2)
printHelper("d2", v2)
var (
d3 = `3.14`
v3 float32
)
json.Unmarshal([]byte(d3), &v3)
printHelper("d3", v3)
var (
d4 = `[1,2]`
v4 []int
)
json.Unmarshal([]byte(d4), &v4)
printHelper("d4", v4)
var (
d5 = `{"a": "b"}`
v5 map[string]string
v6 interface{}
)
json.Unmarshal([]byte(d5), &v5)
printHelper("d5", v5)
json.Unmarshal([]byte(d5), &v6)
printHelper("d5(interface{})", v6)
}
func printHelper(name string, value interface{}) {
fmt.Printf("%s Unmarshal value is: %T, %v \n", name, value, value)
}
运行代码我们可以得到如下输出结果:
d1 Unmarshal value is: bool, false
d2 Unmarshal value is: int, 2
d3 Unmarshal value is: float32, 3.14
d4 Unmarshal value is: []int, [1 2]
d5 Unmarshal value is: map[string]string, map[a:b]
d5(interface{}) Unmarshal value is: map[string]interface {}, map[a:b]
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
)
type Result struct {
Name string `json:"name"`
Score float64 `json:"score"`
}
type Student struct {
Id int `json:"id"`
Name string `json:"name"`
Results []Result `json:"results"`
}
func main() {
dat, _ := ioutil.ReadFile("data.json")
var s Student
json.Unmarshal(dat, &s)
fmt.Printf("Student's result is: %v\n", s)
}
运行代码输出结果为:
Student's result is: {1 小红 [{语文 90} {数学 100}]}
序列化:
package main
import (
"encoding/json"
"io/ioutil"
)
type Result struct {
Name string `json:"name"`
Score float64 `json:"score"`
}
type Student struct {
Id int `json:"id"`
Name string `json:"name"`
Results []Result `json:"results"`
}
func main() {
s := Student{
Id: 1,
Name: "小红",
Results: []Result{
Result{
Name: "语文",
Score: 90,
},
Result{
Name: "数学",
Score: 100,
},
},
}
dat, _ := json.Marshal(s)
ioutil.WriteFile("data2.json", dat, 0755)
}