Go语言:struct、json、map相互转换

Golang语言:struct、json、map相互转换

一、struct、json转换

  1. struct转json示例:

    package main
    
    import (
    	"encoding/json"
    	"fmt"
    )
    
    type Account struct {
    	Name string `json:"user_name"`
    	ID   int32  `json:"user_id"`
    	Age  uint32 `json:"user_age"`
    }
    
    func Struct2Json() {
    	account := Account{
    		Name: "amy",
    		ID:   007,
    		Age:  18,
    	}
    
    	jsonBytes, err := json.Marshal(account)
    	if err != nil {
    		fmt.Println(err)
    	}
    
    	fmt.Println(string(jsonBytes))
    }
    
    func main() {
    	Struct2Json()
    }
    
  2. json转struct示例:

    package main
    
    import (
    	"encoding/json"
    	"fmt"
    )
    
    type Account struct {
    	Name string `json:"user_name"`
    	ID   int32  `json:"user_id"`
    	Age  uint32 `json:"user_age"`
    }
    
    func Json2Struct() {
    	jsonStr := `
    		{
    			"user_name":"amy",
    			"user_id":7,
    			"user_age":18
    		}
    	`
    	account := Account{}
    	json.Unmarshal([]byte(jsonStr), &account)
    	fmt.Println(account)
    }
    func main() {
    	Json2Struct()
    }
    

二、json、map转换

  1. json转map示例:

    func Json2Map() {
    	jsonStr := `
    		{
    			"user_name":"amy",
    			"user_id":7,
    			"user_age":18
    		}
    	`
    	var mapResult map[string]interface{}
    	err := json.Unmarshal([]byte(jsonStr), &mapResult)
    
    	if err != nil {
    		fmt.Println(err)
    	}
    
    	fmt.Println(mapResult)
    }
    
  2. map转json示例:

    func Map2Json() {
    	mapInstances := map[string]interface{}{"user_name": "amy", "user_id": 7, "user_age": 18}
    
    	jsonBytes, err := json.Marshal(mapInstances)
    	if err !=nil{
    		fmt.Println(err)
    	}
    
    	fmt.Println(string(jsonBytes))
    }
    

三、struct、map转换

需要安装一个第三方库
在命令行中运行: go get github.com/goinggo/mapstructure

  1. struct转map示例:

    func Map2Struct() {
    	mapInstances := make(map[string]interface{})
    	mapInstances["Name"] = "amy"
    	mapInstances["ID"] = 7
    	mapInstances["Age"] = 18
    
    	var account Account
    	err := mapstructure.Decode(mapInstances, &account)
    	if err != nil {
    		fmt.Println(err)
    	}
    
    	fmt.Println(account)
    }
    
  2. map转struct示例:

    func Struct2Map() {
    	account := Account{
    		Name: "amy",
    		ID:   007,
    		Age:  18,
    	}
    
    	obj1 := reflect.TypeOf(account)
    	obj2 := reflect.ValueOf(account)
    
    	var data = make(map[string]interface{})
    	for i := 0; i < obj1.NumField(); i++ {
    		data[obj1.Field(i).Name] = obj2.Field(i).Interface()
    	}
    
    	fmt.Println(data)
    }
    

你可能感兴趣的:(Go语言:struct、json、map相互转换)