例子1:把字符串转换成结构体:{"FromUid":"100","FromName":"HANASHAN"}
package mainimport ("fmt""encoding/json")//接收普通消息结构体type receiveMessage struct{FromUid string//发送者uidFromName string//发送者名字}func main(){str := []byte(`{"FromUid":"100","FromName":"HANASHAN"}`)var revMsg receiveMessageerr := json.Unmarshal([]byte(str),&revMsg)fmt.Println(err)fmt.Println(revMsg)}
例子2把 [{"Id2":100,"Title":"木华黎"},{"Id":200,"Title":"耶律楚才"},{"Id":300,"Title":"纳呀啊","Test":100}]转换成go的切片
package mainimport ("encoding/json""fmt""reflect")//接收普通消息结构体type articles struct{Id int //文章idTitle string //文章标题}func main(){//json字符串数组,转换成切片articleStrings := `[{"Id2":100,"Title":"木华黎"},{"Id":200,"Title":"耶律楚才"},{"Id":300,"Title":"纳呀啊","Test":100}]`var articleSlide []map[string]interface{}multiErr := json.Unmarshal([]byte(articleStrings),&articleSlide)if multiErr!=nil{fmt.Println("转换出错:",multiErr)}for k,v:=range articleSlide{fmt.Println("第",k,"个数的值是:",v,v["Id"],v["Title"])}fmt.Println(reflect.TypeOf(articleSlide))}