- Marshaler">type Marshaler
- Unmarshaler">type Unmarshaler
- Decoder">type Decoder
- RawMessage">type RawMessage
- Demo
- TAG
- 隐式继承
- 显示继承
type Marshaler
实现了Marshaler接口的类型可以将自身序列化为合法的json描述。
type Marshaler interface {
MarshalJSON() ([]byte, error)
}
type Unmarshaler
实现了Unmarshaler接口的对象可以将自身的json描述反序列化。该方法可以认为输入是合法的json字符串。如果要在方法返回后保存自身的json数据,必须进行拷贝。
type Unmarshaler interface {
UnmarshalJSON([]byte) error
}
func Marshal(v interface{}) ([]byte, error) //将golang类型转为json
func Unmarshal(data []byte, v interface{}) error //将json转为golang类型
Bool 对应JSON布尔类型
float64 对应JSON数字类型
string 对应JSON字符串类型
[]interface{} 对应JSON数组
map[string]interface{} 对应JSON对象
nil 对应JSON的null
type Decoder
从输入流解码json对象
type Decoder struct {
// contains filtered or unexported fields
}
func NewDecoder(r io.Reader) Decoder
func (dec Decoder) Decode(v interface{}) error
- Decode从输入流读取下一个json编码值并保存在v指向的值里,参见Unmarshal函数的文档获取细节信息
``go const jsonStream =
` type Message struct { Name, Text string } dec := json.NewDecoder(strings.NewReader(jsonStream)) for { var m Message if err := dec.Decode(&m); err == io.EOF {{"Name": "Ed", "Text": "Knock knock."}
{"Name": "Sam", "Text": "Who's there?"}
{"Name": "Ed", "Text": "Go fmt."}
{"Name": "Sam", "Text": "Go fmt who?"}
{"Name": "Ed", "Text": "Go fmt yourself!"}
} else if err != nil {break
} fmt.Printf(“%s: %s\n”, m.Name, m.Text) }log.Fatal(err)
Ed: Knock knock. Sam: Who’s there? Ed: Go fmt. Sam: Go fmt who? Ed: Go fmt yourself!
<a name="VTM4i"></a>
#### type [Encoder](https://github.com/golang/go/blob/master/src/encoding/json/stream.go?name=release#140)
```go
type Encoder struct {
// contains filtered or unexported fields
}
将json对象写入输出流
func NewEncoder(w io.Writer) Encoder
func (enc Encoder) Encode(v interface{}) error
type RawMessage
RawMessage类型是一个保持原本编码的json对象。本类型实现了Marshaler和Unmarshaler接口,用于延迟json的解码或者预计算json的编码。
type RawMessage []byte
func (m *RawMessage) MarshalJSON() ([]byte, error)
func (m *RawMessage) UnmarshalJSON(data []byte) error
Demo
type ConfigStruct struct {
Host string `json:"host"`
Port int `json:"port"`
}
func main() {
jsonStr := `{"host": "http://localhost:9090","port": 9090}`
//json str 转map
var dat map[string]interface{}
if err := json.Unmarshal([]byte(jsonStr), &dat); err == nil {
fmt.Println(dat)//map[host:http://localhost:9090 port:9090]
fmt.Println(dat["host"])//http://localhost:9090
}
//json str 转struct
var config ConfigStruct
if err := json.Unmarshal([]byte(jsonStr), &config); err == nil {
fmt.Println(config)//{http://localhost:9090 9090}
fmt.Println(config.Host)//http://localhost:9090
}
//struct 到json str
if b, err := json.Marshal(config); err == nil {
fmt.Println(string(b))//{"host":"http://localhost:9090","port":9090}
}
//map 到json str
enc := json.NewEncoder(os.Stdout)
enc.Encode(dat)//{"host":"http://localhost:9090","port":9090}
//array 到 json str
arr := []string{"hello", "apple", "python", "golang", "base", "peach", "pear"}
lang, err := json.Marshal(arr)
if err == nil {
fmt.Println(string(lang)) //["hello","apple","python","golang","base","peach","pear"]
}
//json 到 []string
var wo []string
if err := json.Unmarshal(lang, &wo); err == nil {
fmt.Println(wo) //[hello apple python golang base peach pear]
}
}
TAG
type Product struct {
Name string `json:"name"`
ProductID int64 `json:"-"` // 表示不进行序列化
Number int `json:"number,omitempty"` //序列化的时候忽略0值或者空值
Price float64 `json:"price"`
IsOnSale bool `json:"is_on_sale,string"` //指定类型
Persion `json:",inline"` // 展开
}
type Persion struct {
Age int64 `json:"age"`
}
隐式继承
type MyConfigStruct struct{
AAA string `json:"aaa"`
}
type ConfigStruct struct {
MyConfigStruct
Host string `json:"host"`
Port int `json:"port"`
}
func main() {
config := ConfigStruct{
MyConfigStruct{"aaa"},
"127.0.0.1",
3306,
}
if b, err := json.Marshal(config); err == nil {
fmt.Println(string(b))//{"aaa":"aaa","host":"127.0.0.1","port":3306}
var config1 ConfigStruct
if err := json.Unmarshal(b, &config1); err == nil {
fmt.Printf("%+v",config1)//{MyConfigStruct:{AAA:aaa} Host:127.0.0.1 Port:3306}
}
}
}
显示继承
type MyConfigStruct struct{
AAA string `json:"aaa"`
}
type ConfigStruct struct {
My MyConfigStruct `json:"my"`
Host string `json:"host"`
Port int `json:"port"`
}
func main() {
config := ConfigStruct{
MyConfigStruct{"aaa"},
"127.0.0.1",
3306,
}
if b, err := json.Marshal(config); err == nil {
fmt.Println(string(b)) // {"my":{"aaa":"aaa"},"host":"127.0.0.1","port":3306}
var config ConfigStruct
if err := json.Unmarshal(b, &config); err == nil {
fmt.Printf("%+v",config) // {My:{AAA:aaa} Host:127.0.0.1 Port:3306}
}
}
}