golang json序列化
Posted 钢闸门的笔记收藏册
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang json序列化相关的知识,希望对你有一定的参考价值。
结构体序列化
func main() { var j = js{ Name: "zhangsan", Age: 16, Sal: 1500.3, Intro: "aihao lanqiu", } json1, _ := json.Marshal(j) fmt.Println(string(json1)) mp() slic() }
map序列化
func mp() { var a = map[string]interface{}{ "Name": "lisi", "Age": 16, "Sal": 22.33, } js, _ := json.Marshal(a) fmt.Println(string(js)) }
切片序列化
func slic() { var slice = []map[string]interface{}{ map[string]interface{}{ "Name": "lisi", "Age": 16, "Sal": 22.33, }, map[string]interface{}{ "Name": "zhangsan", "Age": 22, "Sal": 1122.33, }, } js, _ := json.Marshal(slice) fmt.Println(string(js)) }
切片序列化后返回的是一个数组,因为切片中包含两个元素,即切片包含两个切片故为一个数组
package main import ( "encoding/json" "fmt" ) type js struct { Name string Age int Sal float32 Intro string } func mp() { var a = map[string]interface{}{ "Name": "lisi", "Age": 16, "Sal": 22.33, } js, _ := json.Marshal(a) fmt.Println(string(js)) } func slic() { var slice = []map[string]interface{}{ map[string]interface{}{ "Name": "lisi", "Age": 16, "Sal": 22.33, }, map[string]interface{}{ "Name": "zhangsan", "Age": 22, "Sal": 1122.33, }, } js, _ := json.Marshal(slice) fmt.Println(string(js)) } func main() { var j = js{ Name: "zhangsan", Age: 16, Sal: 1500.3, Intro: "aihao lanqiu", } json1, _ := json.Marshal(j) fmt.Println(string(json1)) mp() slic() }
基础类型结构化
无意义
package main import ( "encoding/json" "fmt" ) func main() { var a = 1 var s = "abc" a1, _ := json.Marshal(a) s1, _ := json.Marshal(s) fmt.Println(string(a1)) fmt.Println(string(s1)) }
以上是关于golang json序列化的主要内容,如果未能解决你的问题,请参考以下文章