Golang the structure into JSON data by reflection

Source: Internet
Author: User
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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.