Preface
In daily development, we often putJSON
Analyze into the corresponding structure, otherwise it will also convert the structure intoJSON
. This article will be passed nextJSON
Two functions of the package are introducedJSON
Conversion with structure.
Structure to JSON
Marshal(v any) ([]byte, error)
:Willv
Convert toJSON
Data,[]byte
return in the form.
import ( "encoding/json" "fmt" ) type User struct { Name string Age int Height float64 Weight *float64 Child bool marriageStatus string } func main() { weight := 120.5 user := User{ Name: "gopher", Age: 18, Height: 180.5, Weight: &weight, Child: false, marriageStatus: "unmarried", } jsonBytes, err := (user) if err != nil { ("error: ", err) return } (string(jsonBytes)) // {"Name":"gopher","Age":18,"Height":180.5,"Weight":120.5,"Child":false} }
Execution results:
{"Name":"gopher","Age":18,"Height":180.5,"Weight":120.5,"Child":false}
According to the results, we can see:
- The fields cannot be exported (the field name starts with lowercase letters), and cannot be converted to
JSON
ofkey
Yes, this also fitsGo
The syntax stipulates that variables or structure fields starting with lowercase letters cannot be accessed outside the package. - The converted field name is the same as the name of the structure field.
- If the field is a pointer type, the converted value is the field value pointed to by the pointer.
If we want to specify the name after the field is converted, or ignore an exportable field, we can type the structure fieldJSON
Implementation of tags.
import ( "encoding/json" "fmt" ) type User struct { Name string `json:"name"` Age int `json:"age"` Height float64 `json:"height"` Weight *float64 `json:"weight"` Child bool `json:"child"` MarriageStatus string `json:"-"` } func main() { weight := 120.5 user := User{ Name: "gopher", Age: 18, Height: 180.5, Weight: &weight, Child: false, MarriageStatus: "unmarried", } jsonBytes, err := (user) if err != nil { ("error: ", err) return } (string(jsonBytes)) // {"name":"gopher","age":18,"height":180.5,"weight":120.5,"child":false} }
By setting the structure fieldJSON
Tags, can be specified to convertJSON
The field name after that, ifJSON
The value of the label is-
, then it is in conversionJSON
Ignore this field when .
JSON parsing structure
Unmarshal(data []byte, v any) error
:WillJSON
Resolve into the specified structure.
import ( "encoding/json" "fmt" ) type User struct { Name string `json:"name"` Age int `json:"age"` Height float64 `json:"height"` Child bool `json:"-"` marriageStatus string } func main() { userStr := ` { "name": "gopher", "age": 18, "height": 180.5, "child": true, "marriageStatus": "unmarried" } ` user := &User{} err := ([]byte(userStr), &user) if err != nil { ("error: ", err) return } ("%#v", user) // &{Name:"gopher", Age:18, Height:180.5, Child:false, marriageStatus:""} }
Execution results:
&{Name:"gopher", Age:18, Height:180.5, Child:false, marriageStatus:""}
According to the results, we can see:
useUnmarshal
When using a function, we need to pass in the pointer type of the structure, otherwise the value of the structure field will not be changed, because the underlying layer changes the value of the structure field through pointers.
JSON
When parsing,JSON
ofkey
The matching rules with the structure field are:
- Priority search
JSON
Tag values andkey
The same thing, if you find it,value
Assign to the corresponding field. - If not
JSON
Tag value andkey
If match, match according to the field name.
It can be found that if the structure field is a non-export field orJSON
The value of the label is-
, will not be matched.
summary
This article introducesGo
In language,JSON
Conversion with structure. Turn in structureJSON
When we can label the field and specify the convertedkey
Name, it should be noted that if the field of the structure is not exported or fieldJSON
The tag value is-
, in the conversionJSON
will be ignored. on the contraryJSON
The same is true when parsing structures.
This is the article about detailed explanation of the conversion between structures and JSON in Go. For more related Go structures, please search for my previous articles or continue browsing the related articles below. I hope you can support me in the future!