当前位置: 首页 > 工具软件 > gojson > 使用案例 >

go json字符串转换成结构体,json字符串数组转换成切片

向泽语
2023-12-01

例子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))
}

 

 

 

 类似资料: