type Marshaler

实现了Marshaler接口的类型可以将自身序列化为合法的json描述。

  1. type Marshaler interface {
  2. MarshalJSON() ([]byte, error)
  3. }

type Unmarshaler

实现了Unmarshaler接口的对象可以将自身的json描述反序列化。该方法可以认为输入是合法的json字符串。如果要在方法返回后保存自身的json数据,必须进行拷贝。

  1. type Unmarshaler interface {
  2. UnmarshalJSON([]byte) error
  3. }

func Marshal(v interface{}) ([]byte, error) //将golang类型转为json
func Unmarshal(data []byte, v interface{}) error //将json转为golang类型

  1. Bool 对应JSON布尔类型
  2. float64 对应JSON数字类型
  3. string 对应JSON字符串类型
  4. []interface{} 对应JSON数组
  5. map[string]interface{} 对应JSON对象
  6. nil 对应JSONnull

type Decoder

从输入流解码json对象

  1. type Decoder struct {
  2. // contains filtered or unexported fields
  3. }

func NewDecoder(r io.Reader) Decoder
func (dec
Decoder) Decode(v interface{}) error

  • Decode从输入流读取下一个json编码值并保存在v指向的值里,参见Unmarshal函数的文档获取细节信息 ``go const jsonStream =
    1. {"Name": "Ed", "Text": "Knock knock."}
    2. {"Name": "Sam", "Text": "Who's there?"}
    3. {"Name": "Ed", "Text": "Go fmt."}
    4. {"Name": "Sam", "Text": "Go fmt who?"}
    5. {"Name": "Ed", "Text": "Go fmt yourself!"}
    ` type Message struct { Name, Text string } dec := json.NewDecoder(strings.NewReader(jsonStream)) for { var m Message if err := dec.Decode(&m); err == io.EOF {
    1. break
    } else if err != nil {
    1. log.Fatal(err)
    } fmt.Printf(“%s: %s\n”, m.Name, m.Text) }

Ed: Knock knock. Sam: Who’s there? Ed: Go fmt. Sam: Go fmt who? Ed: Go fmt yourself!

  1. <a name="VTM4i"></a>
  2. #### type [Encoder](https://github.com/golang/go/blob/master/src/encoding/json/stream.go?name=release#140)
  3. ```go
  4. type Encoder struct {
  5. // contains filtered or unexported fields
  6. }

将json对象写入输出流
func NewEncoder(w io.Writer) Encoder
func (enc
Encoder) Encode(v interface{}) error

type RawMessage

RawMessage类型是一个保持原本编码的json对象。本类型实现了Marshaler和Unmarshaler接口,用于延迟json的解码或者预计算json的编码。

  1. type RawMessage []byte
  2. func (m *RawMessage) MarshalJSON() ([]byte, error)
  3. func (m *RawMessage) UnmarshalJSON(data []byte) error

Demo

  1. type ConfigStruct struct {
  2. Host string `json:"host"`
  3. Port int `json:"port"`
  4. }
  5. func main() {
  6. jsonStr := `{"host": "http://localhost:9090","port": 9090}`
  7. //json str 转map
  8. var dat map[string]interface{}
  9. if err := json.Unmarshal([]byte(jsonStr), &dat); err == nil {
  10. fmt.Println(dat)//map[host:http://localhost:9090 port:9090]
  11. fmt.Println(dat["host"])//http://localhost:9090
  12. }
  13. //json str 转struct
  14. var config ConfigStruct
  15. if err := json.Unmarshal([]byte(jsonStr), &config); err == nil {
  16. fmt.Println(config)//{http://localhost:9090 9090}
  17. fmt.Println(config.Host)//http://localhost:9090
  18. }
  19. //struct 到json str
  20. if b, err := json.Marshal(config); err == nil {
  21. fmt.Println(string(b))//{"host":"http://localhost:9090","port":9090}
  22. }
  23. //map 到json str
  24. enc := json.NewEncoder(os.Stdout)
  25. enc.Encode(dat)//{"host":"http://localhost:9090","port":9090}
  26. //array 到 json str
  27. arr := []string{"hello", "apple", "python", "golang", "base", "peach", "pear"}
  28. lang, err := json.Marshal(arr)
  29. if err == nil {
  30. fmt.Println(string(lang)) //["hello","apple","python","golang","base","peach","pear"]
  31. }
  32. //json 到 []string
  33. var wo []string
  34. if err := json.Unmarshal(lang, &wo); err == nil {
  35. fmt.Println(wo) //[hello apple python golang base peach pear]
  36. }
  37. }

TAG

  1. type Product struct {
  2. Name string `json:"name"`
  3. ProductID int64 `json:"-"` // 表示不进行序列化
  4. Number int `json:"number,omitempty"` //序列化的时候忽略0值或者空值
  5. Price float64 `json:"price"`
  6. IsOnSale bool `json:"is_on_sale,string"` //指定类型
  7. Persion `json:",inline"` // 展开
  8. }
  9. type Persion struct {
  10. Age int64 `json:"age"`
  11. }

隐式继承

  1. type MyConfigStruct struct{
  2. AAA string `json:"aaa"`
  3. }
  4. type ConfigStruct struct {
  5. MyConfigStruct
  6. Host string `json:"host"`
  7. Port int `json:"port"`
  8. }
  9. func main() {
  10. config := ConfigStruct{
  11. MyConfigStruct{"aaa"},
  12. "127.0.0.1",
  13. 3306,
  14. }
  15. if b, err := json.Marshal(config); err == nil {
  16. fmt.Println(string(b))//{"aaa":"aaa","host":"127.0.0.1","port":3306}
  17. var config1 ConfigStruct
  18. if err := json.Unmarshal(b, &config1); err == nil {
  19. fmt.Printf("%+v",config1)//{MyConfigStruct:{AAA:aaa} Host:127.0.0.1 Port:3306}
  20. }
  21. }
  22. }

显示继承

  1. type MyConfigStruct struct{
  2. AAA string `json:"aaa"`
  3. }
  4. type ConfigStruct struct {
  5. My MyConfigStruct `json:"my"`
  6. Host string `json:"host"`
  7. Port int `json:"port"`
  8. }
  9. func main() {
  10. config := ConfigStruct{
  11. MyConfigStruct{"aaa"},
  12. "127.0.0.1",
  13. 3306,
  14. }
  15. if b, err := json.Marshal(config); err == nil {
  16. fmt.Println(string(b)) // {"my":{"aaa":"aaa"},"host":"127.0.0.1","port":3306}
  17. var config ConfigStruct
  18. if err := json.Unmarshal(b, &config); err == nil {
  19. fmt.Printf("%+v",config) // {My:{AAA:aaa} Host:127.0.0.1 Port:3306}
  20. }
  21. }
  22. }