gojson字符串转换成结构体,json字符串数组转换成切⽚例⼦1:把字符串转换成结构体:{"FromUid":"100","FromName":"HANASHAN"}
package main
import (
"fmt"
"encoding/json"
)
//接收普通消息结构体
type receiveMessage struct{
FromUid string  //发送者uid
FromName string //发送者名字
}
func main(){
str := []byte(`{"FromUid":"100","FromName":"HANASHAN"}`)
var revMsg receiveMessage
err := 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 main
import (
"encoding/json"
"fmt"
"reflect"
)
//接收普通消息结构体
type articles struct{
Id int  //⽂章id
Title 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))
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。