美文网首页
Golang -- Json序列化

Golang -- Json序列化

作者: None_Ling | 来源:发表于2021-09-22 21:45 被阅读0次

    简述

    在使用Go Struct的Json Marshal的时候,通过Json To Go Struct工具可以生成结构体,但是当在结构体中只对部分属性赋值的时候,Marshal后的字符串与预期不符,如下所示:

    当定义了Host中包含A、B、C三个结构体时,如果只为其中一个结构赋值,我们期望Json中只包含这一个结构体的值。

    func main() {
        host := Host{
            OA: A{
                Content: "oa",
            },
        }
        data, _ := json.Marshal(host)
        fmt.Printf("data:%s", string(data))
    }
    
    // A
    type A struct {
        Content string `json:"content1"`
        Text string `json:"content2"`
    }
    
    // B
    type B struct {
        Content string `json:"content3"`
    }
    
    // C RTX富文本内容文本类型
    type C struct {
        Content string `json:"content4"`
    }
    
    // RichText RTX富文本内容
    type Host struct {
        OA A `json:"text1"`
        OB B `json:"text2"`
        OC C `json:"text3"`
    }
    
    

    当其他属性为空时,不要将该属性加入Json串中,但是实际上会输出。

    // 期望值
    data:{"text1":{"content1":"oa"}}
    // 实际值
    data:{"text1":{"content1":"oa","content2":""},"text2":{"content3":""},"text3":{"content4":""}}
    

    omitempty的作用

    当为所有结构体(HostABC)中都加入了omitempty标记后,运行后发生如下变化:

    data:{"text1":{"content1":"oa"},"text2":{},"text3":{}}
    

    omitempty只能作用于string或者int等简单类型的数据,而无法作用于结构体对象。

    结构体指针

    当遇见该种情况时,则需要使用结构体指针即可解决

    func main() {
        host := Host{
                    // 将A的指针传入
            OA: &A{
                Content: "oa",
            },
        }
        data, _ := json.Marshal(host)
        fmt.Printf("data:%s", string(data))
    }
    
    // A
    type A struct {
        Content string `json:"content1,omitempty"`
        Text int `json:"content2,omitempty"`
    }
    
    // B
    type B struct {
        Content string `json:"content3,omitempty"`
    }
    
    // C RTX富文本内容文本类型
    type C struct {
        Content string `json:"content4,omitempty"`
    }
    
    // RichText RTX富文本内容
    type Host struct {
            // 复杂结构体都使用指针定义,同时声明omitempty即可
        OA *A `json:"text1,omitempty"`
        OB *B `json:"text2,omitempty"`
        OC *C `json:"text3,omitempty"`
    }
    

    得到的输出:

    data:{"text1":{"content1":"oa"}}
    

    参考资料

    Go's "omitempty" explained
    How to not marshal an empty struct into JSON with Go?

    相关文章

      网友评论

          本文标题:Golang -- Json序列化

          本文链接:https://www.haomeiwen.com/subject/fpiggltx.html