golang map,json,struct相互转换

==Json转Map==

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    jsonStr := `
        {
                "name": "张三",
                "age": 18
        }
        `

    var mapResult map[string]interface{}
    err := json.Unmarshal([]byte(jsonStr), &mapResult)
    if err != nil {
        fmt.Println(err)
        return
    }

    fmt.Println(mapResult)
}

 

==Json转Struct==

package main

import (
    "encoding/json"
    "fmt"
)

type People1 struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func main() {
    jsonStr := `
        {
                "name": "张三",
                "age": 12
        }
        `
    var people People1
    err := json.Unmarshal([]byte(jsonStr), &people)
    if err != nil {
        fmt.Println(err)
        return
    }

    fmt.Println(people)
}

 

==Map转Json==

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    var mapInstances []map[string]interface{}
    instance1 := map[string]interface{}{"name": "张三", "age": 18}
    instance2 := map[string]interface{}{"name": "李四", "age": 35}
    mapInstances = append(mapInstances, instance1, instance2)

    jsonStr, err := json.Marshal(mapInstances)
    if err != nil {
        fmt.Println(err)
        return
    }

    fmt.Println(string(jsonStr))
}

 

==Map转Struct==

安装插件:go get github.com/goinggo/mapstructure

package main

import (
    "fmt"
    "github.com/goinggo/mapstructure"
)

type People3 struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

// go get github.com/goinggo/mapstructure
func main() {
    mapInstance := make(map[string]interface{})
    mapInstance["Name"] = "张三"
    mapInstance["Age"] = 18

    var people People3
    err := mapstructure.Decode(mapInstance, &people)
    if err != nil {
        fmt.Println(err)
        return
    }

    fmt.Println(people)
}

 

==Struct转Json==

package main

import (
    "encoding/json"
    "fmt"
)

type People2 struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func main() {
    p := People2{
        Name: "张三",
        Age:  18,
    }

    jsonBytes, err := json.Marshal(p)
    if err != nil {
        fmt.Println(err)
        return
    }

    fmt.Println(string(jsonBytes))
}

 

==Struct转Map==

package main

import (
    "fmt"
    "reflect"
)

type People4 struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func main() {
    people := People4{"张三", 18}

    obj1 := reflect.TypeOf(people)
    obj2 := reflect.ValueOf(people)

    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)
}

 

posted @ 2022-04-06 22:04  大墨垂杨  阅读(193)  评论(0编辑  收藏  举报