如何在Go中使用模糊嵌入来JSON序列化结构?

时间:2017-12-01 20:10:58

标签: json go

似乎同时IdentityReport嵌入CommonProperties会导致遗漏CompositeObject的JSON序列化中的所有公共字段。

package main

import (
    "encoding/json"
    "fmt"
    "time"
)

type CommonProperties struct {
    Type         string    `json:"type,omitempty"`
    ID           string    `json:"id,omitempty"`
    CreatedByRef string    `json:"created_by_ref,omitempty"`
    Created      time.Time `json:"created,omitempty"`
    Modified     time.Time `json:"modified,omitempty"`
    Revoked      bool      `json:"revoked,omitempty"`
    Labels       []string  `json:"labels,omitempty"`
    Confidence   int       `json:"confidence,omitempty"`
    Language     string    `json:"lang,omitempty"`
}

type Identity struct {
    CommonProperties
    Name               string   `json:"name,omitempty"`
    Description        string   `json:"description,omitempty"`
    IdentityClass      string   `json:"identity_class,omitempty"`
    Sectors            []string `json:"sectors,omitempty"`
    ContactInformation string   `json:"contact_information,omitempty"`
}

type Report struct {
    CommonProperties
    Name        string    `json:"name,omitempty"`
    Description string    `json:"description,omitempty"`
    Published   time.Time `json:"published,omitempty"`
    ObjectRefs  []string  `json:"object_refs,omitempty"`
}

type CompositeObject struct {
    InternalID string `json:"uid,omitempty"`
    Pending    bool   `json:"pending"`
    Type       string `json:"type"`

    *Identity
    *Report
}

func main() {
    co := CompositeObject{
        Type:    "report",
        Pending: true,
        Report: &Report{
            Name:        "Spear Phishing Report",
            Description: "...",
            Published:   time.Date(2016, 5, 12, 8, 17, 27, 0, time.UTC),
            ObjectRefs: []string{
                "indicator--26ffb872-1dd9-446e-b6f5-d58527e5b5d2",
                "campaign--83422c77-904c-4dc1-aff5-5c38f3a2c55c",
                "relationship--f82356ae-fe6c-437c-9c24-6b64314ae68a",
            },
            CommonProperties: CommonProperties{
                ID:           "report--84e4d88f-44ea-4bcd-bbf3-b2c1c320bcb3",
                Type:         "report",
                Created:      time.Date(2016, 5, 12, 8, 17, 27, 0, time.UTC),
                CreatedByRef: "identity--a463ffb3-1bd9-4d94-b02d-74e4f1658283",
                Modified:     time.Date(2016, 5, 12, 8, 17, 27, 0, time.UTC),
            },
        },
    }
    json, _ := json.Marshal(&co)
    fmt.Println(string(json))
}

播放链接:

第二个通过注释掉第二个CommonProperties嵌入来获得所需的输出。

我不明白为什么这种歧义的嵌入会阻止JSON序列化。有没有一个解决方案不涉及编写一堆MarshalJSON()函数?

0 个答案:

没有答案