golang的结构体,字典与json字符串之间的相互转换,json.Marshal()与json.Unmarshal()函数

1、结构体

package main

import (
	"encoding/json"
	"fmt"
)

type User struct {
	Name   string
	Age    int64
	Height float64
	Weight float64
}

func main() {
	user := User{
		Name:   "小花",
		Age:    18,
		Height: 162,
		Weight: 42,
	}
	// struct--转-->json string
	str_json, err := json.Marshal(user)
	if err != nil {
		fmt.Printf("json.Marshal failed, err:%v\n", err)
		return
	}
	fmt.Printf("str_json:%s\n", str_json)
	// json string--转-->struct
	var struct_user User
	err = json.Unmarshal(str_json, &struct_user)
	if err != nil {
		fmt.Printf("json.Unmarshal failed, err:%v\n", err)
		return
	}
	fmt.Printf("struct_user:%#v\n", struct_user)
}

// 打印结果
str_json:{"Name":"小花","Age":18,"Height":162,"Weight":42}
struct_user:main.User{Name:"小花", Age:18, Height:162, Weight:42}

2、字典 

package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	var m = make(map[string]interface{}, 1)
	fmt.Printf("打印字典: %v\n", m)
	m["count"] = 1 // int
	fmt.Printf("打印字典: %v\n", m)
	// map --转--> json string
	b, err := json.Marshal(m)
	if err != nil {
		fmt.Printf("marshal failed, err:%v\n", err)
	}
	// 转换后的结果为字节组,str_byte:[]byte{0x7b, 0x22, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x22, 0x3a, 0x31, 0x7d}
	fmt.Printf("str_byte: %#v\n", b)
	// string()函数:将字节转换成字符串
	// 打印结果:str:"{\"count\":1}"
	fmt.Printf("str: %#v\n", string(b))

	// json string -> map[string]interface{}
	var m2 map[string]interface{}
	err = json.Unmarshal(b, &m2)
	// 结果:map字典: map[count:1]
	fmt.Printf("map字典: %v\n", m2) // 1
	if err != nil {
		fmt.Printf("unmarshal failed, err:%v\n", err)
		return
	}
	// 结果:count值:1
	fmt.Printf("count值:%v\n", m2["count"]) // 1
	fmt.Printf("type:%T\n", m2["count"])  // float64
}

 

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页