咔咔博客之json文件解码为map和结构体
【GO】50 编码map为json文件说了map转json文件
案例:json转为map
package main
import (
"encoding/json"
"fmt"
"os"
)
/**
json解码为go
*/
func main() {
file, e := os.OpenFile("d:/kaka.json", os.O_RDONLY, 0666)
if e != nil {
fmt.Println("文件打开失败")
} else {
fmt.Println("json文件打开成功")
}
// 文件挂起执行完关闭文件
defer file.Close()
// 创建解码器
decoder := json.NewDecoder(file)
mMap := make(map[string]interface{})
e = decoder.Decode(&mMap)
fmt.Println(e)
if e != nil {
fmt.Println("文件解码失败")
} else {
// 文件解码成功 map[like:[撸代码 你猜] name:咔咔 咔咔博客地址:blog.fangkang.top 咔咔手赚网地址:fangkang.top]
fmt.Println("文件解码成功", mMap)
}
}
json转为结构体
package main
import (
"encoding/json"
"fmt"
"os"
)
type persons struct {
Name string
Like []string
}
/**
json解码为结构体
*/
func main() {
file, e := os.OpenFile("d:/kaka.json", os.O_RDONLY, 0666)
if e != nil {
fmt.Println("文件打开失败")
} else {
fmt.Println("json文件打开成功")
}
// 文件挂起执行完关闭文件
defer file.Close()
// 创建解码器
decoder := json.NewDecoder(file)
// 创建的本来就是一个指针
perPtr := new(persons)
err := decoder.Decode(perPtr)
if err != nil {
fmt.Println("文件解码失败")
} else {
//文件解码成功 &{咔咔 [撸代码 你猜]}
fmt.Println("文件解码成功", perPtr)
}
}
案例注意点
- json转结构体时,结构体的属性需要大写。new一个结构体出来就是指针
- 接送转map时需要传入map指针