2016-07-21 41 views
3

我真的希望下面的代碼能夠工作,但是目前我不需要手動將值從一個結構設置到另一個結構。有沒有一種很好的方法來暴露JSON有效載荷中的某些結構屬性?

https://play.golang.org/p/yfcsaNJm9M

package main 

import "fmt" 
import "encoding/json" 

type A struct { 
    Name  string `json:"name"` 
    Password string `json:"password"` 
} 

type B struct { 
    A 
    Password string `json:"-"` 
    Locale string `json:"locale"` 
} 

func main() { 

    a := A{"Jim", "some_secret_password"} 
    b := B{A: a, Locale: "en"} 

    data, _ := json.Marshal(&b) 
    fmt.Printf("%v", string(data)) 
} 

輸出......我不想表現的祕密領域

{"name":"Jim","password":"some_secret_password","locale":"en"} 
+3

https://play.golang.org/p/HdwIssr-oC是你期待? –

+0

這就是我正在尋找:)我永遠不會期望,但工作。 – chris

+0

@PravinMishra你應該發佈是作爲答案 –

回答

1

結構值編碼爲JSON對象。每個導出結構字段 成爲對象除非

- the field's tag is "-", or 
- the field is empty and its tag specifies the "omitempty" option. 

空值是假,0,任何零指針或接口值的成員,和 任何陣列,切片,地圖,或串長度爲零。該對象的默認 鍵字符串是結構字段名稱,但可以在結構 字段的標記值中指定。結構字段的標記值中的「json」鍵是鍵名稱 ,後跟可選的逗號和選項。例子:

// Field is ignored by this package. 
Field int `json:"-"` 

// Field appears in JSON as key "myName". 
Field int `json:"myName"` 

// Field appears in JSON as key "myName" and 
// the field is omitted from the object if its value is  empty, 
// as defined above. 
Field int `json:"myName,omitempty"` 

// Field appears in JSON as key "Field" (the default), but 
// the field is skipped if empty. 
// Note the leading comma. 
Field int `json:",omitempty"` 

所以,你的代碼應該是:

package main 

import "fmt" 
import "encoding/json" 

type A struct { 
    Name  string `json:"name"` 
    Password string `json:"password"` 
} 

type B struct { 
    A 
    Password string `json:"password,omitempty"` 
    Locale string `json:"locale"` 
} 

func main() { 

    a := A{"Jim", "some_secret_password"} 
    b := B{A: a, Locale: "en"} 

    data, _ := json.Marshal(&b) 
    fmt.Printf("%v", string(data)) 
} 

https://play.golang.org/p/HdwIssr-oC

相關問題