Golangデータ型変換(json、struct、map)


Golangデータ型変換


一、struct回転json


方法1

package main

import (
	"encoding/json"
	"fmt"
)

type Server struct {
	ServerName string `json:"serverName,string"`
	ServerIP   string `json:"serverIP,omitempty"`
}
type Serverslice struct {
	Did     string
	Servers Server `json:"servers"`
}


func main() {
	//  struct     
	var s Serverslice
	s.Servers = Server{ServerName: "Beijing_Base", ServerIP: "127.0.02"}
	//  (.   )    
	s.Did = "111"
	b, err := json.Marshal(s)
	if err != nil {
		fmt.Println("JSON ERR:", err)
	}
	fmt.Println(s.Did)
	fmt.Println(string(b))
}	

出力結果:
111
{"Did":"111","servers":{"serverName":"\"Beijing_Base\"","serverIP":"127.0.02"}}


方法2
package main

import (
	"encoding/json"
	"fmt"
	"github.com/bitly/go-simplejson"
)
type Auth struct {
	With   string `json:"with"`
	AppKey string
	ReqId  int
	Ts     string
	Sign   string  `json:"sign,omitempty"`
}
type ReqBody struct {
	Td     string `json:"td"` //      Td=》td
	Authen Auth
	Did    string
	Mid    string `json:"mid,omitempty"`//omitempty  :      nil 0 (  0,   "",   [] ),    JSON         
}

func main() {
	//    struct  
	var rb ReqBody
	var auth0 Auth
	//     
	auth0 = Auth{With: "aa_a", AppKey: "2323", ReqId: 1, Ts: "tttsss"}
	rb = ReqBody{Td: "1111", Authen: auth0, Did: "11101"}
	//     
	rb.Authen.Sign = "GGGGGGGGGGGGG"
	rb.Td = "222"
	//struct json
	c, err := json.Marshal(rb)
	if err != nil {
		fmt.Println("JSON ERR:", err)
	}
	d := string(c)
	fmt.Println(d)
	
	//  simplejson     .Get()    (   []byte)
	x, err := simplejson.NewJson([]byte(d))
	re := *x.Get("Did")
	fmt.Println(re)
	
	//    
	setbody(rb)
}
func setbody(ax interface{}) {
	jm, _ := json.Marshal(ax)
	fmt.Println(string(jm))

}

出力結果

{"td":"222","Authen":{"with":"aa_a","AppKey":"2323","ReqId":1,"Ts":"tttsss","sign":"GGGGGGGGGGGGG"},"Did":"11101"}
{11101}
{"td":"222","Authen":{"with":"aa_a","AppKey":"2323","ReqId":1,"Ts":"tttsss","sign":"GGGGGGGGGGGGG"},"Did":"11101"}

二、簡単json回転map

package main
import (
	"encoding/json"
	"fmt"
)
func main() {
	json_str := "{\"IP\": \"127.0.0.1\", \"name\": \"SKY\"}"
	by := []byte(json_str)
	m := make(map[string]string)
	errs := json.Unmarshal(by, &m)
	if errs != nil {
		fmt.Println("Umarshal failed:", errs)
		return
	}
	fmt.Println("m:",m)
	fmt.Println("m.ip:", m["IP"])

}

結果は次のとおりです.
m: map[IP:127.0.0.1 name:SKY]
m.ip: 127.0.0.1

例2

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    json_str := "{\"device\": \"1\",\"data\": [{\"humidity\": \"27\",\"time\": \"2017-07-03 15:23:12\"}]}"
    m := make(map[string]interface{})
    err := json.Unmarshal([]byte(json_str), &m)
    fmt.Println(err)
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println(m["device"])
        data := m["data"]
        if v, ok := data.([]interface{})[0].(map[string]interface{}); ok {
            fmt.Println(ok, v["humidity"], v["time"])
        }
    }
}

実行結果

1
true 27 2017-07-03 15:23:12