2016-07-21 3 views
3

Ich hatte wirklich gehofft, dass der untenstehende Code funktionieren würde, aber ich muss jetzt nicht manuell Werte von einer Struktur zur anderen setzen.Gibt es eine gute Möglichkeit, bestimmte Strukturattribute in Json-Payloads nicht verfügbar zu machen?

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)) 
} 

Ausgang ... Ich will nicht das Geheimnis Feld als JSON-Objekte

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

https://play.golang.org/p/HdwIssr-oC ist, dass Sie erwartet? –

+0

Das ist, was ich suche :) Ich hätte nie erwartet, dass das funktioniert. – chris

+0

@ PravinMishra sollten Sie als Antwort posten –

Antwort

1

Struct Werte kodieren zeigen. Jede exportierte struct Feld wird Mitglied des Objekts, es sei denn

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

Die leeren Werte falsch sind, 0, jeder nil Zeiger oder Schnittstellenwert, und jede Array, Scheibe, Karte, oder eine Kette von Länge Null. Die Standardschlüsselschlüsselzeichenfolge des Objekts ist der Name des Strukturfelds, kann jedoch im Tag-Wert des Felds 'struct ' angegeben werden. Der Schlüssel "json" im Tag-Wert des Strukturfelds ist der Schlüsselname, gefolgt von einem optionalen Komma und Optionen. Beispiele:

// 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"` 

So sollte Ihr Code sein:

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

Verwandte Themen