码迷,mamicode.com
首页 > Web开发 > 详细

JSON 数据

时间:2019-12-01 13:34:56      阅读:83      评论:0      收藏:0      [点我收藏+]

标签:style   结构体   结构   bool   slice   back   app   struct   print   

 

结构体数据转json

 1 package main 
 2 
 3 import (
 4     "fmt"
 5     "encoding/json"
 6 
 7     )
 8 
 9 
10 //结构体
11 type Person struct {
12     Name string
13     Age int
14     Rmb float64
15     Sex bool
16     Hobby []string
17 }
18 
19 
20 
21 
22 func main() {
23 Person :=Person{"小小",50,123.45,true,[]string{"","",""}}
24 
25 bytes,err := json.Marshal(Person)
26 if err !=nil{
27     fmt.Println("序列化失败,err=",err)
28     return
29 }
30     fmt.Println(string(bytes)) //强制类型转换bytes转为string
31 }
32 
33 /*
34 {"Name":"小小","Age":50,"Rmb":123.45,"Sex":true,"Hobby":["吃","喝","玩"]}
35 */

 

map转json

 

 

 1 package main 
 2 
 3 import (
 4     "fmt"
 5     "encoding/json"
 6 
 7     )
 8 
 9 func main() {
10     dataMap :=make(map[string]interface{}) //stings做键,空接口做数值,任意类型。
11     dataMap["Name"]=""
12     dataMap["Age"]=50
13     dataMap["Rmb"]=123.45
14     dataMap["Sex"]=true    
15     dataMap["Hobby"]=[]string{"","",""}
16 
17 
18     bytes,err := json.Marshal(dataMap)
19 if err !=nil{
20     fmt.Println("序列化失败,err=",err)
21     return
22 }
23     fmt.Println(string(bytes)) //强制类型转换bytes转为string
24 
25 }
26 /*
27 {"Age":50,"Hobby":["吃","喝","玩"],"Name":"小","Rmb":123.45,"Sex":true}
28 */

 

 切片转JSON

 

 

 1 package main 
 2 
 3 import (
 4     "fmt"
 5     "encoding/json"
 6 
 7     )
 8 
 9 func main() {
10 
11     dataMap1 :=make(map[string]interface{}) //stings做键,空接口做数值,任意类型。
12     dataMap1["Name"]=""
13     dataMap1["Age"]=50
14 
15 
16     dataMap2 :=make(map[string]interface{}) //stings做键,空接口做数值,任意类型。
17     dataMap2["Name"]=""
18     dataMap2["Age"]=60
19 
20     //将数据添加到切片中
21      dataSlice := make([]map[string]interface{},0)
22      dataSlice = append(dataSlice,dataMap1,dataMap2)
23 
24 
25     bytes,err := json.Marshal(dataSlice)
26 if err !=nil{
27     fmt.Println("序列化失败,err=",err)
28     return
29 }
30     fmt.Println(string(bytes)) //强制类型转换bytes转为string
31 
32 }
33 
34 /*
35 [{"Age":50,"Name":"小"},{"Age":60,"Name":"大"}]
36 */

 

 

 

 

 

JSON 数据

标签:style   结构体   结构   bool   slice   back   app   struct   print   

原文地址:https://www.cnblogs.com/chaoyangxu/p/11965658.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!