golang 結構體中空數組被序列化成null解決方法


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM