【Go】JSON库(二)之JSON转结构体、map、切片

2021-09-16 10:42:53 浏览数 (1)

1. json转map

代码语言:javascript复制
package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	jsonStr := `{"Name":"于谦","Age":50,"Rmb":123.22,"Sex":true,"Hobby":["eat","drink"]}`
	JsonBytes := []byte(jsonStr)
	data_map := make(map[string]interface{})
	err := json.Unmarshal(JsonBytes, &data_map)
	
	if err!= nil{
		fmt.Println("err=",err)
		return
	}
	fmt.Println(data_map)
}
  1. 把json转换为结构体
代码语言:javascript复制
package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	jsonStr := `{"Name":"于谦","Age":50,"Rmb":123.22,"Sex":true,"Hobby":["eat","drink"]}`
	JsonBytes := []byte(jsonStr)

	type Person1 struct {
		Name string
		Age int
		Rmb float64
		Sex bool
		Hobby []string
	}
	p := new(Person1)
	err = json.Unmarshal(JsonBytes, &p)
	if err != nil{
		fmt.Println(err)
		return
	}
	fmt.Println(*p)
}
  1. JSON转map切片
代码语言:javascript复制
package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	jsonStr1 := `[{"age":12,"hobby":["eat","read"],"name":"王小波","rmb":2322214.14,"sex":true},{"age":19,"hobby":["run","read"],"name":"王波","rmb":2324.14,"sex":true}]`
	bytes1 := []byte(jsonStr1)
	i := make([]map[string]interface{}, 0)
	err2 := json.Unmarshal(bytes1, &i)
	if err2 != nil{
		fmt.Println(err)
		return
	}
	fmt.Println(i)
}
  1. JSON转结构体切片
代码语言:javascript复制
package main

import (
	"encoding/json"
	"fmt"
)

func main() {

	type Person1 struct {
		Name string
		Age int
		Rmb float64
		Sex bool
		Hobby []string
	}

	jsonStr1 := `[{"age":12,"hobby":["eat","read"],"name":"王小波","rmb":2322214.14,"sex":true},{"age":19,"hobby":["run","read"],"name":"王波","rmb":2324.14,"sex":true}]`
	bytes1 := []byte(jsonStr1)
	persons := make([]Person1, 0)
	err4 := json.Unmarshal(bytes1, &persons)
	if err4 != nil{
		fmt.Println(err4)
		return
	}
	fmt.Println(persons)
}

0 人点赞