1、interface{} 转 struct 结构体

1)第一种:interface 强转 struct
1
2
3
4
5
6
7
8
9
10
newUser:=user{
Id: 1,
Name: "杉杉",
}

var newInterface1 interface{}

//第一种使用interface
newInterface1=newUser
fmt.Printf("使用interface: %v",newInterface1.(user))
2)第二种:json.Marshal 和 Unmarshal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//第二种使用json
var newInterface2 interface{}
// interface赋值,省略...
// 将interface数据转换为byte[]
resByte, err := json.Marshal(newInterface2)
if err != nil {
fmt.Printf("%v",err)
return
}
var newData user
if err = json.Unmarshal(resByte, &newData); err != nil {
fmt.Printf("%v",err)
}
fmt.Printf("使用 json: %v",newData)

2、golang json 返回不需要输出的 struct 字段

  • 使用tag json:”-“
  • 结构体字段首字母小写

更多可参考:https://segmentfault.com/q/1010000015957994

3、