博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Go 系列教程 —— 33. golang中struct、json、map互相转化
阅读量:5242 次
发布时间:2019-06-14

本文共 4726 字,大约阅读时间需要 15 分钟。

结构体生成Json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package
main
 
import
(
    
"encoding/json"
    
"fmt"
)
 
type
IT
struct
{
    
Company string `json:
"-"
`
//此字段不会输出到屏幕
    
//Company  string   `json:"company"`       这样打印输出别名首字母就会小写(二次编码)
    
Subjects []string `json:
"subjects"
`
//二次编码
    
IsOk     bool     `json:
",string"
`
    
Price    float64  `json:
",string"
`
}
 
func
main() {
    
//定义一个结构体变量,同时初始化
    
s := IT{
"itcast"
, []string{
"Golang"
,
"PHP"
,
"Java"
,
"C++"
}, true, 666.666}
 
    
//编码,根据内容生成json文本
    
//buf, err := json.Marshal(s)
    
//buf =  {"subjects":["Golang","PHP","Java","C++"],"IsOk":"true","Price":"666.666"}
    
buf, err := json.MarshalIndent(s,
""
,
"    "
)
//格式化编码
    
if
err != nil {
        
fmt.Println(
"err = "
, err)
        
return
    
}
 
    
fmt.Println(
"buf = "
, string(buf))
}

  

1
2
3
4
5
6
7
8
9
10
11
//结果
buf =  {
        
"subjects"
: [  
//首字母小写
               
"Golang"
,
                
"PHP"
,
                
"Java"
,
                
"C++"
        
],
       
"IsOk"
:
"true"
,  
//string类型
       
"Price"
:
"666.666"
}

  Json转成结构体

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package
main
 
import
(
    
"encoding/json"
    
"fmt"
)
 
type
IT
struct
{
    
Address   string   `json:
"address"
`
    
Languages []string `json:
"languages"
`
//二次编码
    
Status    bool     `json:
"isok"
`
    
Price     float64  `json:
"price"
`
}
 
func
main() {
 
    
jsonBuf := `
    
{
    
"address"
:
"北京"
,
    
"languages"
: [
        
"Golang"
,
        
"PHP"
,
        
"Java"
,
        
"Python"
    
],
    
"status"
: true,
    
"price"
: 666.666
}`
 
    
var
tmp IT                                  
//定义一个结构体变量
    
err := json.Unmarshal([]byte(jsonBuf), &tmp)
//第二个参数要地址传递
    
if
err != nil {
        
fmt.Println(
"err = "
, err)
        
return
    
}
    
//fmt.Println("tmp = ", tmp)
    
fmt.Printf(
"tmp = %+v\n"
, tmp)
 
    
type
IT2
struct
{
        
Subjects []string `json:
"languages"
`
//二次编码
    
}
 
    
var
tmp2 IT2
    
err = json.Unmarshal([]byte(jsonBuf), &tmp2)
//第二个参数要地址传递
    
if
err != nil {
        
fmt.Println(
"err = "
, err)
        
return
    
}
    
fmt.Printf(
"tmp2 = %+v\n"
, tmp2)
 
}

  

1
2
tmp = {Address:北京 Languages:[Golang PHP Java Python] Status:false Price:666.666}
tmp2 = {Subjects:[Golang PHP Java Python]}

  Map生成Json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package
main
 
import
(
    
"encoding/json"
    
"fmt"
)
 
func
main() {
    
//创建一个map
    
m := make(
map
[string]
interface
{}, 4)
//因为类型多,可以用interface空接口
    
m[
"address"
] =
"北京"
    
m[
"languages"
] = []string{
"Golang"
,
"PHP"
,
"Java"
,
"Python"
}
    
m[
"status"
] = true
    
m[
"price"
] = 666.666
 
    
//编码成json
    
//result, err := json.Marshal(m)
    
//result =  {"address":"北京","languages":["Golang","PHP","Java","Python"],"price":666.666,"status":true}
    
result, err := json.MarshalIndent(m,
""
,
"    "
)
    
if
err != nil {
        
fmt.Println(
"err = "
, err)
        
return
    
}
    
fmt.Println(
"result = "
, string(result))
}

  

1
2
3
4
5
6
7
8
9
10
11
result =  {
        
"address"
:
"北京"
,
        
"languages"
: [
                
"Golang"
,
                
"PHP"
,
                
"Java"
,
                
"Python"
        
],
        
"price"
: 666.666,
        
"status"
: true
}

  Json转化为Map

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package
main
 
import
(
    
"encoding/json"
    
"fmt"
)
 
func
main() {
    
jsonBuf := `
    
{
    
"company"
:
"itcast"
,
    
"subjects"
: [
        
"Go"
,
        
"C++"
,
        
"Python"
,
        
"Test"
    
],
    
"isok"
: true,
    
"price"
: 666.666
}`
 
    
//创建一个map
    
m := make(
map
[string]
interface
{}, 4)
 
    
err := json.Unmarshal([]byte(jsonBuf), &m)
//第二个参数要地址传递
    
if
err != nil {
        
fmt.Println(
"err = "
, err)
        
return
    
}
    
fmt.Printf(
"m = %+v\n"
, m)
 
    
//    var str string
    
//    str = string(m["company"]) //err, 无法转换
    
//    fmt.Println("str = ", str)
 
    
var
str string
 
    
//类型断言, 值,它是value类型
    
for
key, value :=
range
m {
        
//fmt.Printf("%v ============> %v\n", key, value)
        
switch
data := value.(
type
) {
        
case
string:
            
str = data
            
fmt.Printf(
"map[%s]的值类型为string, value = %s\n"
, key, str)
        
case
bool:
            
fmt.Printf(
"map[%s]的值类型为bool, value = %v\n"
, key, data)
        
case
float64:
            
fmt.Printf(
"map[%s]的值类型为float64, value = %f\n"
, key, data)
        
case
[]string:
            
fmt.Printf(
"map[%s]的值类型为[]string, value = %v\n"
, key, data)
        
case
[]
interface
{}:
            
fmt.Printf(
"map[%s]的值类型为[]interface, value = %v\n"
, key, data)
        
}
 
    
}
 
}

  

1
2
3
4
map
[address]的值类型为string, value = 北京
map
[Languages]的值类型为[]
interface
, value = [Golang PHP Java Python]
map
[Status]的值类型为bool, value = true
map
[price]的值类型为float64, value = 666.666000

  []interface{}转json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package
main
  
import
(
    
"encoding/json"
    
"fmt"
)
func
main(){
    
var
s []
interface
{}
    
s = append(s,5)
    
s = append(s,[]string{
"Golang"
,
"PHP"
,
"Java"
,
"Python"
})
    
s = append(s,
map
[string]string{
"hello"
:
"world"
})
    
result, err := json.MarshalIndent(s,
""
,
"    "
)
    
if
err != nil {
        
fmt.Println(
"err = "
, err)
        
return
    
}
    
fmt.Println(
"result = "
, string(result))
}

  

1
2
3
4
5
6
7
8
9
10
11
12
result =  [
    
5,
    
[
        
"Golang"
,
        
"PHP"
,
        
"Java"
,
        
"Python"
    
],
    
{
        
"hello"
:
"world"
    
}
]

  

转载于:https://www.cnblogs.com/fengchuiyizh/p/11564136.html

你可能感兴趣的文章
3.PHP 教程_PHP 语法
查看>>
Duilib扩展《01》— 双击、右键消息扩展
查看>>
利用Fiddler拦截接口请求并篡改数据
查看>>
python习题:unittest参数化-数据从文件或excel中读取
查看>>
Android控件之GridView探究
查看>>
在工程中要加入新的错误弹出方法
查看>>
PS 滤镜— — sparkle 效果
查看>>
snmpwalk命令常用方法总结
查看>>
网站产品设计
查看>>
代理ARP
查看>>
go 学习笔记(4) ---项目结构
查看>>
java中静态代码块的用法 static用法详解
查看>>
Java线程面试题
查看>>
Paper Reading: Relation Networks for Object Detection
查看>>
Java IO流学习总结
查看>>
day22 01 初识面向对象----简单的人狗大战小游戏
查看>>
mybatis源代码分析:深入了解mybatis延迟加载机制
查看>>
Flask三剑客
查看>>
Hibernate-缓存
查看>>
【BZOJ4516】生成魔咒(后缀自动机)
查看>>