golang json转struct结构体

// convert json to struct

package main


import (
    "fmt"
    "encoding/json"
)

type Host struct {
    IP string
    Name string
}

func main() {

    b := []byte(`{"IP": "192.168.11.22", "name": "SKY"}`)

    m := Host{}

    err := json.Unmarshal(b, &m)
    if err != nil {

        fmt.Println("Umarshal failed:", err)
        return
    }


    fmt.Println("m:", m)
    fmt.Println("m.IP:", m.IP)
    fmt.Println("m.Name:", m.Name)
}

output:

m: {192.168.11.22 SKY}
m.IP: 192.168.11.22
m.Name: SKY

你可能感兴趣的:(Golang)