golang json 转 map 和 struct

package main

import (
    "encoding/json"
    "fmt"
)

type User struct {
    Name    string `json:"name"`
    IsAdmin bool   `json:"is_admin"`
}

func JsontoStruct() {
    jsonStr := `
        {
            "name":"Nick",
            "is_admin":true
        }
    `
    var user User
    json.Unmarshal([]byte(jsonStr), &user)
    fmt.Println("user:", user)
}

func StructToJson() {
    user := User{
        Name:    "Nick",
        IsAdmin: true,
    }
    fmt.Println("user:", user)
    jsonBytes, err := json.Marshal(user)
    if err != nil {
        fmt.Println("序列化失败")
        return
    }
    fmt.Println("json:", string(jsonBytes))
}

func JsonToMap() {
    jsonStr := `
        {
            "name":"Nick",
            "is_admin":true
        }
    `
    var mapRes map[string]interface{}
    if err := json.Unmarshal([]byte(jsonStr), &mapRes); err != nil {
        fmt.Println("json转map失败")
        return
    }
    fmt.Println("map:", mapRes)
}

func MapToJson() {
    testMap := make(map[string]interface{})
    testMap["name"] = "Nick"
    testMap["is_admin"] = true

    jsonBytes, err := json.Marshal(testMap)
    if err != nil {
        fmt.Println("map转json失败")
    }
    fmt.Println("map转换成的json串:", string(jsonBytes))
}

func main() {
    JsontoStruct()
    StructToJson()
    JsonToMap()
    MapToJson()
}
打赏作者

您将是第一位评论人!

提醒
avatar