Go生成json和解json数据都很简单,通过官方的“encoding/json”包,调用json.Marshal( )生成数据,调用json.Unmarshal( )或json.NewDecoder.Decode( )解析数据。
package main
import (
"encoding/json"
"fmt"
"io"
"os"
"strings"
)
type Order struct {
Name string `json:name`
OrderItem []Item `json:item`
OrderRefund []Refund `json:refund`
}
type Item struct {
Name string `json:name`
Oid int `json:oid`
}
type Refund struct {
Name string `json:name`
Item int `json:item`
Content string `json:content`
Imgs string `json:imgs`
Status string `json:status`
}
// json转结构体
func jsonToStruct() {
const jsonStream = `
{"Id": 11, "Name": "a"}
{"Id": 22, "Name": "b"}
{"Id": 33, "Name": "c"}
{"Id": 44, "Name": "d"}
{"Id": 55, "Name": "e"}
`
dec := json.NewDecoder(strings.NewReader(jsonStream))
for {
var m Message
err := dec.Decode(&m)
if err == io.EOF {
break
} else if err != nil {
fmt.Println(err)
} else {
fmt.Printf("%d: %s\n", m.Id, m.Name)
}
}
}
// 结构体转json
func structToJson() {
var m Order
m.Name = "10010"
m.OrderItem = append(m.OrderItem, Item{Ono: "Shanghai_Hourse", Oid: 1})
m.OrderItem = append(m.OrderItem, Item{Ono: "Beijing_Hourse", Oid: 2})
for i := 1; i < 6; i++ {
str := []byte("Things")
str = strconv.AppendInt(str, int64(i), 10)
orderi := Item{Ono: string(str), Oid: i}
m.OrderItem = append(m.OrderItem, orderi)
}
bytes, _ := json.Marshal(m)
fmt.Printf("json:m,%s\n", bytes)
}
func main() {
jsonToStruct()
structToJson()
}
有疑问加站长微信联系(非本文作者)