Introduction JSON format is one of our most commonly used serialization formats, the go language as a Google-developed, known as the Internet language of the C language, and naturally the JSON format support is very good. But the go language is a strong type language, the format requirements are very strict and JSON format, although there are types, but not stable, the go language when parsing the source of non-strongly typed languages such as PHP serialized JSON, often encountered some problems such as the change in the field type caused by the failure of normal parsing situation, Cause the service to be unstable. So the main purpose of this article
- is to excavate the vast majority of Golang parsing json.
- A more elegant solution to the various problems that exist when parsing JSON
- Go into the process of Golang parsing JSON
- Golang parsing JSON's tag chapter
What is the normal serialization of a struct?
Package Mainimport ( "Encoding/json" " fmt")//Product product information type product struct { Name string ProductID Int64 number int price float64 isonsale bool}func Main () { p: = & product{} p.name = "Xiao mi 6" P.isonsale = True P.number = 10000 P.price = 2499.00 P.productid = 1 Data, _: = json. Marshal (p) FMT. PRINTLN (string data)}//result {"Name": "Xiao mi 6", "ProductID": 1, "number": 10000, "price": 2499, "Isonsale": true}
2. What is Tag,tag is a label, a label for each field of the struct, a label before the colon is a type, followed by a sign
Product _type product struct { name string ' json: ' name ' ' ProductID Int64 ' JSON: "-" '// Indicates that number int ' JSON is not serialized: ' Number ' ' price float64 ' JSON: ' price ' ' Isonsale BOOL ' JSON: "is_on_sale,string" '}//after serialization, you can see {"name": "Xiao mi 6", "Number": 10000, "price": 2499, "Is_on_ Sale ":" false "}
3. Omitempty,tag with Omitempy, can ignore the 0 value or null value when serializing
Package Mainimport ( "Encoding/json" " fmt")//product _type product struct { Name string ' JSON: ' Name "' ProductID Int64 ' JSON:" Product_id,omitempty "' number int ' JSON: ' number ' ' Price float64 ' JSON: ' price ' Isonsale bool ' JSON: ' Is_on_sale,omitempty ' '}func main () { p: = &product{} p.name = "Xiao mi 6" P.isonsale = False P.number = 10000 P.price = 2499.00 p.productid = 0 data, _: = json. Marshal (p) FMT. PRINTLN (string data)}//result {"name": "Xiao mi 6", "Number": 10000, "Price": 2499}
4. Type, sometimes, when serializing or deserializing, we may have inconsistent struct type and required type, this time can be specified, support String,number and Boolean
Package Mainimport ( "Encoding/json" " fmt")//product _type product struct { Name string ' JSON: ' Name "' ProductID Int64 ' JSON:" product_id,string "' number int ' JSON:" number,string "' Price float64 ' JSON: ' price,string ' ' isonsale bool ' JSON: ' is_on_sale,string ' '}func main () { var data = ' {' "name": "Xiao mi 6", "product_id": "Ten", "Number": "10000", "Price": "2499", "Is_on_sale": "True"} ' P: = &product{} Err: = json. Unmarshal ([]byte (data), p) FMT. PRINTLN (Err) FMT. Println (*p)}//results <nil>{xiao mi 6 10000 2499 true}
- Let's talk about Golang. How to customize parsing Json,golang with JSON parsing capabilities very powerful
Description
Many times, we may encounter such a scenario, that is, the remote return of the JSON data is not the type you want, or you want to do additional operations, such as in the process of parsing validation, or type conversion, then we can or in the parsing process of data conversion
Instance
Package Mainimport ("bytes" "Encoding/json" "FMT")//mail _type mail struct {Value string}//Unmarshaljson _ Func (M *mail) unmarshaljson (data []byte) error {//Here is a simple demonstration, simple to determine if bytes. Contains (data, []byte ("@")) {return FMT. Errorf ("Mail format Error")} M.value = string (data) return nil}//Unmarshaljson _func (M *mail) Marshaljson () (d ATA []byte, err Error) {if m! = Nil {data = []byte (m.value)} return}//phone _type phone struct {Va Lue string}//Unmarshaljson _func (P *phone) Unmarshaljson (data []byte) error {//Here is a simple demonstration, simple to determine if Len (data)! = 1 1 {return FMT. Errorf ("Phone format error")} P.value = string (data) return nil}//Unmarshaljson _func (P *phone) Marshaljson () (data []byte, err Error) {if P! = Nil {data = []byte (p.value)} return}//userrequest _type userrequest struct {Name string Mail Mail Phone phone}func main () {User: = userrequest{} user. Name = "Ysy" User. Mail.value = "[email protected]" user. Phone.value = "18900001111" FMT. PRINTLN (JSON. Marshal (User)}
Why are you doing this?
If it is client-side development, you need to develop a lot of APIs, receive a lot of JSON, in the early development of the definition of various types seems to be a lot of work, rather than write if else to judge the data simple violence. But by the end of the development, you will find that a predefined approach can greatly improve your code quality and reduce the amount of code. Below example 1 and instance 2, who can reduce the code at a glance
Instance 1,if else do data check//userrequest _type userrequest struct { Name string Mail string Phone string} Func AddUser (data []byte) (err error) { User: = &userrequest{} err = json. Unmarshal (data, user) if err! = Nil { return } // if IsMail (user. Mail) { return FMT. Errorf ("Mail format error") } if Isphone (user. Phone) { return FMT. Errorf ("Phone format error") } //TODO return} instance 2, using a pre-defined type, to be judged at parse Time//Userrequest _type userrequest struct { Name string mail mail Phone phone}func AddUser (data []byte) { User: = &userrequest{} err = json. Unmarshal (data, user) if err! = Nil { return } //TODO}
Transferred from: http://www.cnblogs.com/yangshiyu/p/6942414.html
Golang JSON usage Explained