Golang struct包含struct时,json忽略空值

Golang struct结构体包含struct时,json后忽略空值

Posted by Ricky on May 29, 2018

前言

在使用golang的结构体时,如果在json里面打tag omitempty,那么json时,如果该字段是空值,那么久不会被json编码, 但是 结构体里面包含了另一个结构体,还这么写的话,是没有效果的,这个时候就需要给子结构体前面加*号,指针

上代码

package main

import (
	"encoding/json"
	"fmt"
)

type CustomerMsgData struct {
	Touser   string `json:"touser"`
	Msgtype  string `json:"msgtype"`
	*TextMsg  `json:"text,omitempty"`
	*ImageMsg `json:"image,omitempty"`
	*VoiceMsg `json:"voice,omitempty"`
	*NewsMsg  `json:"news,omitempty"`
}

type TextMsg struct {
	Content string `json:"content"`
}

type ImageMsg struct {
	MediaID string `json:"media_id"`
}

type VoiceMsg struct {
	MediaID string `json:"media_id"`
}

type NewsMsg struct {
	Articles `json:"articles"`
}

type Articles []struct {
	Title       string `json:"title,omitempty"`
	Description string `json:"description,omitempty"`
	URL         string `json:"url,omitempty"`
	Picurl      string `json:"picurl,omitempty"`
}

func main() {
	sendMsg := &CustomerMsgData{} //待发送的数据
	jsssss, _ := json.Marshal(sendMsg)
	fmt.Println(string(jsssss))
}

打印结果:

{"touser":"","msgtype":""}