syfun / example

Example for Python, Golang, Shell and Configs of some tools.
MIT License
1 stars 0 forks source link

Golang JSON #2

Open syfun opened 6 years ago

syfun commented 6 years ago

Marshal

func Marshal(v interface{}) ([]byte, error)

调用流程

  1. 如果v实现了Marshaler接口,而且v不是nil指针,Marshal会调用v的MarshalJSON方法生成json

  2. 如果没有MarshalJSON方法,但是实现了encoding.TextMarshaler接口,那么调用MarshalText方法,最终生成一个字符串

  3. 如果都没有的话,按照默认的方式执行

Go和Json的类型对应

go type json type
boolean boolean
floating point, integer and other number number
string utf-8 string
array, slice array
[]byte base64-encoded string
nil null
struct object

"<", ">", "&" will be escaped to "\u003c", "\u003e", "\u0026", to keep some browsers from misinterpreting JSON output as HTML. This escaping can be disabled using an Encoder that had SetEscapeHTML(false) called on it.

结构体

结构体会被编码成json对象, 每一个可导出字段(exported struct field, 即首字母大写字段)都会成为对象的key, key的名称默认是字段名称(也可以通过添加json标签来修改).

type Example struct {
    Field1 string `json:"field1"`   // key是field1
    Field2 int    `json:"field2,omitempty"` // key是field2,如果为空, 那么json中就会没有这个Key
    Field3 string `json:",omitempty"`  // key是Field3, 如果为空, 那么json中就会没有这个Key
    Field4 string `json:"-"`  // 忽略
    Field5 string `json:"-,"`  // key是-
    Field6 int    `json:"field6,string"` // key是field6, 值会转成string
    Field7 string
    other  string  // 忽略
}

{"field1", "field2", "field3", "field4", "field5", 10, "field7", ""}

# Marshal to

{"field1":"field1","field2":"field2","Field3":"field3","-":"field5","field6":"10","Field7":"field7"}

{"field1", "", "", "field4", "field5", 20, "field7", ""}

# Marshal to

{"field1":"field1","-":"field5","field6":"20","Field7":"field7"}

匿名结构体

实现MarshalJSON时,如果需要对某个具体的field进行修改(比如时间转时间戳),那么可以使用如下方法。

func (example *Example) MarshalJSON() ([]byte, error) {
    type Alias Example
    return json.Marshal(struct {
        Other string
        *Alias
    }{
        example.other,
        (*Alias)(example),
    })
}

map

map的key必须是string, integer type, 或者实现了encoding.TextMarshaler。

优先级:

  1. string直接使用
  2. encoding.TextMarshaler ## 有疑问
  3. integer转成string

其他

  1. 指针 => 它所指向的值
  2. 接口 => 它所包含的具体指
  3. Channel, complex, function不能转换, 否则报错UnsupportedTypeError

源码

json

syfun commented 5 years ago

json-and-go