In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Go structure serialization of how to achieve, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can gain something.
We will go back to the showMovieHandler method we wrote earlier and update it to return a JSON response that represents a single movie information in the system. Similar to:
{"id": 123," title ":" Casablanca "," runtime ": 102,102," genres ": [" drama "," romance "," war "]," version ": 1}
Instead of using map serialization to create this JSON object (as we did in the previous section), this time we will code a custom Movie structure.
First, you need to define a Movie structure. We will do this in a new internal/data package that will later extend the logic used to encapsulate all custom data types in the project and to interact with the database.
If you follow the steps in the article, create a new internal/data directory that contains a movies.go file:
$mkdir internal/data$ touch internal/data/movies.go
In this new file, define the Movie structure, like this:
File: internal/data/movies.go
Package mainimport ("time") type Movie struct {ID int64 / / unique integer ID CreatedAt time.Time / / time to create the movie to the database Title string / / Movie title Year int32 / / Movie release year Runtime int32 / / Movie duration Genres [] string / / Movie genre (romance, Comedies, etc.) Version int32 / / version number starts from 1 Increase with each update}
It is important to note that all fields in the Movie structure are exportable (that is, starting with an uppercase letter), which is necessary for Go's encoding/json package to be visible. When you encode a structure as JSON, it does not contain any unexported fields.
Now that the structure is defined, let's update the showMovieHandler handler to initialize an instance of the Movie structure and then use the writeJSON () helper function to send it to the client as a JSON response.
The implementation is simple:
File: cmd/api/movies.go
Package mainimport ("fmt"net/http"time"greenlight.alexedwards.net/internal/data") func (app * application) showMovieHandler (w http.ResponseWriter, r * http.Request) {id, err: = app.readIDParam (r) if err! = nil {http.NotFound (w, r) return} / / create an instance of the Move structure containing ID fictional data parsed from the request URL. Notice that the Year field movie: = date.Movie {ID: id, CreateAt: time.now (), Title: "Casablanca", Runtime: 102, Genres: [] string {"drama", "romance", "war"}, Version: 1,} / / serializes the structure to JSON and sends the HTTP response to the client err = app.writeJSON (w) Http.StatusOK, movie, nil) if err! = nil {app.logger.Println (err) http.Error (w, "The server encountered a problem and could not process your request", http.StatusInternalServerError)}}
Ok, try it next!
In this return, there are a few interesting things to point out:
The Movie structure is encoded as a JSON object, with field names and values as key / value pairs.
By default, the key in the JSON object is equal to the field name in the structure (ID, CreatedAt, Title, and so on). We will discuss how to customize the JSON key later.
If the structure instance field is not explicitly assigned, the zero value of the field is serialized to the json value. You can see it in the response above-- we didn't set a value for the Year field in the Go code, but it still appears in the JSON output with a value of 0.
Change the key in the JSON object
One advantage of serializing structures in Go is that you can customize JSON by using struct tag comment fields.
Perhaps the most common use of the struct tag is to change the key name that appears in the JSON object. This is useful when your structure field name is not suitable for public display, or when you want to use a different case style in your JSON output.
File: internal/data/movies.go
/ / use tags to annotate the Movie structure to control how json-encoded key is displayed. Type Movie struct {ID int64 `json: "id" `CreateAt time.Time `json: "created_at" `Title string `json: "title" `Year int32 `json: "year" `Runtime int32 `json: "runtime" `Genres [] string `json: "genres" `Version int32 `json: "version" `}
If you restart the server and access localhost:4000/v1/movies/123 again, you should see a response with a snake key similar to this:
Hide the structure field in the JSON object
You can use the-(hyphen) instruction when you do not want a specific structural field to appear in the JSON output. This is useful for fields that contain internal system information that is not relevant to the user or sensitive information that you do not want to disclose, such as password hashes.
Conversely, when and only if the struct field value is empty, the omitempty instruction hides the field in the JSON output, where empty is defined as:
Equal to false,0 or ""
Empty array, slice or map
Nil pointer or interface value is nil
To demonstrate how to use these instructions, we make more modifications to the Movie structure. The CreatedAt field has nothing to do with our end user, so we use the-directive to hide it in the output. We will also use the omitempty directive to hide the Year, Runtime, and types fields in the output, if and only if they are empty.
Continue and update the struct tag as follows:
File:interface/data/movies.go
Package data....type Movie struct {ID int64 `json: "id" `CreateAt time.Time `json: "-" `/ / use-directive Title string `json: "title" `Year int32 `json: "year,omitempty"` / / add omitempty Runtime int32 `json: "runtime,omitempty" `/ / add omitempty Genres [] string `json: "genres
If you want to use omitempty without changing the key name, you can leave it blank in the struct tag-such as: json: ", omitempty". Note that a comma is necessary.
Now, when you restart the application and refresh your web browser, you should see the following response:
We can see here that the CreatedAt structure field no longer appears in JSON, and the Year field (value 0) does not appear, thanks to the omitempty directive.
Note: you can also prevent it from appearing in JSON serialization by simply setting the structure field to non-exportable. But using the json: "-" flag is usually a better option: explicitly tell the reader that you don't want the field to be included in the json.
In older versions of go vet, an error was caused if you tried to use struct tags on unexported fields, but this has been fixed in go 1.16.
Attach content structure body tag string instruction
The last less commonly used struct marking instruction is string. You can use this label to explicitly indicate that the field values are serialized to the JSON string type. For example, if we want the value of the Runtime field to be represented as a JSON string instead of a number, we can use the string directive like this:
Type Movie struct {ID int64 `json: "id" `CreateAt time.Time `json: "-" `/ / use-instruction Title string `json: "title" `Year int32 `json: "year,omitempty" `Runtime Runtime `json: "runtime,omitempty,string" `Genres [] string `json: "genres,omitempty" `Version int32 `json: "version"`}
The result of JSON serialization is as follows:
{"id": 123," title ":" Casablanca "," runtime ":" 102", / / this is the string "genres": ["drama", "romance", "war"], "version": 1}
Note that the string directive is valid only for fields of type int, uint, float*, or bool. Has no effect on any other type of structural body field.
Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
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.