In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
How to use golang source code analysis json.Marshal, for this problem, this article details the corresponding analysis and solution, hoping to help more small partners who want to solve this problem find a simpler and easier way.
Golang structs can be annotated like @JsonProperty("id") in Java. A string enclosed in backquotes inside a struct is called a Tag.
type Cyeam struct {
Url string `json:"url"`
Other string `json:"-"`
}
By adding the definition of json's Tag to Tag, you can control the format of the output. Also, if the Tag of the json field is defined as-, it will not be resolved.
Such a powerful function, with the help of reflect package, it is not difficult to achieve.
c := Cyeam{Url: "blog.cyeam.com", Other: "... "}
var t reflect.Type
t = reflect.TypeOf(c)
var v reflect.Value
v = 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, you can get its Type and Value. The t.NumField() method gets the number of values contained in the structure, and t.Field(i) gets the value of the variable at the index value. With these two methods, it is possible to traverse structure variables. t.Field(i).Tag.Get("json") gets the Tag of the current field and gets the Tag value of json from it. In this way, we can complete the traversal of the structure and the final generation of the JSON stream.
About how to use golang source code analysis json.Marshal questions to share the answer here, I hope the above content can be of some help to everyone, if you still have a lot of doubts not solved, you can pay attention to the industry information channel to learn more related knowledge.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.