zoukankan      html  css  js  c++  java
  • 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
    
    ghghgjhgjhgh
  • 相关阅读:
    控制器的设计与实现(五)
    综述(一)
    需求分析与数据库设计(二)
    对MVC架构简单概述设计(三)
    排球计分规则——记分员
    Java程序员必看书籍
    java面试必背知识点
    深入浅出UML
    从svn检出的项目缺少.project和.classpath文件解决办法
    打印函数 lodop
  • 原文地址:https://www.cnblogs.com/just-do/p/14724755.html
Copyright © 2011-2022 走看看