golang結構體里面空數組會被序列化成null,但是在寫接口的時候前端會要求數組類型變量沒有數據的話就傳空數組,這種情況可以先定義一個數組類型然后重寫該數組類型的MarshalJSON()方法,當數組的長度是0的時候直接返回json.Marshal([]interface{}{})就可以了。
/*
* Author: oy
* Email: oyblog@qq.com
* Date: 2021/6/13 20:13
* File : unit_test.go
*/
package script
import (
"encoding/json"
"fmt"
"testing"
)
type Ints []int
func (i Ints) MarshalJSON() ([]byte, error) {
if len(i) == 0 {
return json.Marshal([]interface{}{})
} else {
var tempValue []interface{} // 這里需要重新定義一個變量,再序列化,否則會造成循環調用
for _, item := range i {
tempValue = append(tempValue, item)
}
return json.Marshal(tempValue)
}
}
type TestStruct struct {
Ids []int
Id1 Ints
Ids2 Ints
}
func Test(t *testing.T) {
ids2 := []int{1, 2, 3, 4}
testStruct := TestStruct{}
testStruct.Ids2 = ids2 //不需要將ids2定義成Ints,用原有的類型就可以了
marshal, _ := json.Marshal(testStruct)
fmt.Println(string(marshal))
}
=== RUN Test
{"Ids":null,"Id1":[],"Ids2":[1,2,3,4]}
--- PASS: Test (0.00s)
PASS
