This is a creation in Article, where the information may have evolved or changed.
Golang structure can be added similar to Java inside the @JsonProperty("id")
comment. A string enclosed in a struct by an inverted quotation mark is called tag.
type Cyeam struct {Url string `json:"url"`Other string `json:"-"`}
By adding a definition of the JSON tag to the tag, you can control the output format. Also, if the tag of the JSON field is defined -
, it will not be parsed.
This powerful feature, with the help of the reflect
package, is not difficult to achieve.
c := Cyeam{Url: "blog.cyeam.com", Other: "..."}var t reflect.Typet = reflect.TypeOf(c)var v reflect.Valuev = reflect.ValueOf(c)json := "{"for i := 0; i < t.NumField(); i++ {if t.Field(i).Tag.Get("json") != "-" {json += "\"" + t.Field(i).Tag.Get("json") + "\":\"" + v.FieldByName(t.Field(i).Name).String() + "\""}}json += "}"fmt.Println(json){"url":"blog.cyeam.com"}
For each object, it is possible to get the type of it and the value values. The t.NumField()
method can get the number of the included value in the structure, and t.Field(i)
can get the value of the variable at the index value. With these two methods, the structure variables can be traversed. t.Field(i).Tag.Get("json")
you can get the tag of the current field, and get the tag value of the JSON from it. As a result, the traversal of the struct and the concatenation of the final JSON stream are accomplished.
Please refer to the complete source code in this article.
###### References + "1" http://golang.org/pkg/reflect/-the Go programming language+ "2" Source file src/pkg/encoding/ Json/encode.go-the Go Programming Language