1、结构体 -> json串
package main
import (
"encoding/json"
"fmt"
// "log"
"os"
)
type Address struct {
Type string
City string
Country string
}
type VCard struct {
FirstName string
LastName string
Addr []*Address
Remark string
}
func main() {
// 将结构体转换成json str
addr1 := &Address{"home", "gz", "cn"}
addr2 := &Address{"comp", "hz", "cn"}
vc := VCard{"Li", "JingLe", []*Address{addr1, addr2}, "remark1"}
jsonStr, _ := json.Marshal(vc)
fmt.Printf("JSON format: %s\n", jsonStr)
// 生成Writer,可以写入文件
file, _ := os.OpenFile("/Users/lijingle/Downloads/vcard.json", os.O_CREATE|os.O_WRONLY, 0666)
defer file.Close()
enc := json.NewEncoder(file)
enc.Encode(vc)
fmt.Printf("JSON from: %v\n", vc)
}
2、 json -> object
package main
import (
"encoding/json"
"fmt"
// "os"
)
type Address struct {
Type string
City string
Country string
}
type VCard struct {
FirstName string
LastName string
Addr []*Address
Remark string
}
func main() {
jsonObj := []byte(`{"FirstName":"Li","LastName":"JingLe","a":"1","Addr":[{"Type":"home","City":"gz","Country":"cn"},{"Type":"comp","City":"hz","Country":"cn"}],"Remark":"remark1"}`)
// f 指向的值是一个 map,key 是一个字符串,value 是自身存储作为空接口类型的值:
// 这种方式灵活但很麻烦
var f interface{}
json.Unmarshal(jsonObj, &f)
m := f.(map[string]interface{})
for k, v := range m {
switch vv := v.(type) {
case string:
fmt.Println(k, "is string value = ", vv)
case int:
fmt.Println(k, "is int value = ", vv)
case []interface{}:
fmt.Println(k, "is an array:")
for i, u := range vv {
fmt.Println(i, u)
}
default:
fmt.Println(k, "is of a type I don’t know how to handle")
}
}
// 解析到指定构建体. json多了少了也无所谓,试了下能够正常解析
var card VCard;
json.Unmarshal(jsonObj, &card)
fmt.Printf("%s\n", card.FirstName)
}
网友评论