JSON 是一种轻量级的数据交换格式,常用作前后端数据交换,本文基于Go标准库 encoding/json 介绍常用的操作

定义公用数据结构

1
2
3
4
5
6
type Person struct {
	Name string `json:"name"`
	Age  int32  `json:"age"`
}

person := &Person{Name: "guest",Age:  22,}

常用操作分为两大类,序列化和反序列化

序列化(编码)

  • json.NewEncoder(fp).Encode(V)

  • json.Marshal(&v)

写入json到文件

json.NewEncoder(fp).Encode(v)

1
2
3
4
5
6
7
file, err := os.Create("./1.json")
if err != nil {
    log.Fatal("create file error", err)
}
defer file.Close()
encoder := json.NewEncoder(file)
encoder.Encode(person)

Json序列化对象

json.Marshal 只支持以下数据类型

  • bool for JSON booleans

  • float64 for JSON numbers

  • string for JSON strings

  • nil for JSON null

1
2
3
4
5
jsonPerson, err := json.Marshal(person)
if err != nil {
    log.Fatal("marshal struct error",err)
}
fmt.Println(string(jsonPerson))

反序列化(解码)

  • json.NewDecoder(fp).decode(&v)

  • json.Unmarshal([]byte, &v)

从文件读json

1
2
3
4
5
6
7
8
file, err = os.OpenFile("./1.json", os.O_RDONLY, 0666)
defer file.Close()
if err != nil {
    log.Fatal("open file error", err)
}
decoder := json.NewDecoder(file)
decoder.Decode(&newPerson)
fmt.Println(newPerson)

反序列化json对象

一、已知json数据格式

json.Unmarshal([]byte, &v)

1
2
3
4
// 初始化接受对象go struct
var newPerson Person
json.Unmarshal(jsonPerson, &newPerson)
fmt.Println(newPerson)

二、未知json数据格式

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
var newPerson interface{}
json.Unmarshal(jsonPerson, &newPerson)
m := newPerson.(map[string]interface{})
for k, v := range m {
    switch vv := v.(type) {
    case string:
        fmt.Println(k, "is string", vv)
    case float64:
        fmt.Println(k, "is float64", 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")
    }
}

Struct Tag

决定 Marshal 和 Unmarshal 函数如何序列化和反序列化数据

  • omitempty

告诉 Marshal 函数如果 field 的值是对应类型的 zero-value,那么序列化之后的 JSON object 中不包含此 field:

1
2
3
type Person struct {
	Name string `json:"name,omitempty"`
}
  • -

表示跳过当前字段

1
2
3
type Person struct {
	Age  int32  `json:"-"`
}

自定义json序列化方法

整个struct对象

实现对象的 MarshalJSON() 和 UnmarshalJSON()方法

注意: MarshalJSON 方法中的字符串前后【"】是必须的

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
func (p *Person) MarshalJSON() ([]byte, error) {
	marshalStr := "\""
	marshalStr += strings.ToUpper(p.Name)
	marshalStr += "|"
	marshalStr += strconv.Itoa(int(p.Age + 5))
	marshalStr += "\""
	return []byte(marshalStr), nil
}

func (p *Person) UnmarshalJSON(data []byte) error {
	parts := strings.Split(string(data), "|")
	p.Name = strings.TrimLeft(parts[0], "\"")
	t, _ := strconv.Atoi(strings.TrimRight(parts[1], "\""))
	p.Age = int32(t)
	return nil
}

之后正常序列化反序列化

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
person := &Person{Name: "guest",Age:  22,}
jsonPerson, err := json.Marshal(person)
if err != nil {
    log.Fatal("marshal struct error", err)
}
fmt.Println("Marshal", string(jsonPerson))
var newPerson Person
json.Unmarshal(jsonPerson, &newPerson)
fmt.Println("Unmarshal", newPerson)
fmt.Println(newPerson.Name,newPerson.Age)

输出

1
2
3
Marshal "GUEST|27"
Unmarshal {GUEST 27}
GUEST 27

某个字段

假如想将name在序列化的时候改为大写,可以定义一个string的类型别名,实现 MarshalJSON() 和 UnarshalJSON() 方法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
type UpperString string

type Person struct {
	Name UpperString `json:"name"`
	Age  int32       `json:"age"`
}

func (s *UpperString) MarshalJSON() ([]byte, error) {
	return []byte("\""+strings.ToUpper(string(*s))+"\""), nil
}

func (s *UpperString) UnmarshalJSON(data []byte) error {
	*s = UpperString(data)
	return nil
}

func main(){
    person := &Person{Name: "guest",Age:  22,}
    jsonPerson, err := json.Marshal(person)
    if err != nil {
        log.Fatal("marshal struct error", err)
    }
    fmt.Println("Marshal", string(jsonPerson))
    var newPerson Person
    json.Unmarshal(jsonPerson, &newPerson)
    fmt.Println("Unmarshal", newPerson)
    fmt.Println(newPerson.Name,newPerson.Age)
}

输出结果:

1
2
3
Marshal {"name":"GUEST","age":22}
Unmarshal {"GUEST" 22}
"GUEST" 22