2016-01-20 25 views
1

我想編組的this struct部分:如何覆蓋Go結構中的json標記?

type ValueSet struct { 
    Id   string      `json:"id" bson:"_id"` 
    Url   string      `bson:"url,omitempty" json:"url,omitempty"` 
    Identifier *Identifier     `bson:"identifier,omitempty" json:"identifier,omitempty"` 
    Version  string      `bson:"version,omitempty" json:"version,omitempty"` 
    Name   string      `bson:"name,omitempty" json:"name,omitempty"` 
    Status  string      `bson:"status,omitempty" json:"status,omitempty"` 
    Experimental *bool      `bson:"experimental,omitempty" json:"experimental,omitempty"` 
    Publisher string      `bson:"publisher,omitempty" json:"publisher,omitempty"` 
    Contact  []ValueSetContactComponent `bson:"contact,omitempty" json:"contact,omitempty"` 
    Date   *FHIRDateTime    `bson:"date,omitempty" json:"date,omitempty"` 
    LockedDate *FHIRDateTime    `bson:"lockedDate,omitempty" json:"lockedDate,omitempty"` 
    Description string      `bson:"description,omitempty" json:"description,omitempty"` 
    UseContext []CodeableConcept   `bson:"useContext,omitempty" json:"useContext,omitempty"` 
    Immutable *bool      `bson:"immutable,omitempty" json:"immutable,omitempty"` 
    Requirements string      `bson:"requirements,omitempty" json:"requirements,omitempty"` 
    Copyright string      `bson:"copyright,omitempty" json:"copyright,omitempty"` 
    Extensible *bool      `bson:"extensible,omitempty" json:"extensible,omitempty"` 
    CodeSystem *ValueSetCodeSystemComponent `bson:"codeSystem,omitempty" json:"codeSystem,omitempty"` 
    Compose  *ValueSetComposeComponent `bson:"compose,omitempty" json:"compose,omitempty"` 
    Expansion *ValueSetExpansionComponent `bson:"expansion,omitempty" json:"expansion,omitempty"` 
} 

其爲圍棋實施HL7 FHIR,僅包括元數據字段的部分,並省略了三個內容三個字段(codeSystem,組成和膨脹)。我不能(也不應該)更改原始源代碼中的JSON標籤,因爲其他代碼在很大程度上依賴於它的寫作方式。我怎麼能告訴json.Marshal覆蓋這些結構元素上的現有JSON標籤?

回答

4

你不能改變它,但你不必。

最簡單的解決方案是創建你自己的結構,定義你自己的JSON標籤(你希望它們如何出現在輸出中),複製字段,並編組你的結構的值。

E.g.假設您想要編組IdUrl字段,則:

type MyValueSet struct { 
    Id string `json:"MyId"` 
    Url string `json:"MyUrl"` 
} 

var vs ValueSet = ... // Comes from somewhere 

mvs := MyValueSet { 
    Id: vs.Id, 
    Url: vs.Url, 
} 

data, err := json.Marshal(&mvs) 
// Check err