Golnand is a special language that relies on the size of the glyphs to determine access to the domain, rather than using the keyword-limited access as the traditional java,c++.
Look at an example:
An analytic structure is defined here.
Type Response struct {
Code Int64
MSG string
Data string
}
Performing JSON parsing
Func Main () {
var resp Response
Err:=json. Unmarshal ([]byte (' {"Code": $, "MSG": "Success", "Data": "Macbook Pro 2018"} '), &RESP)
If Err!=nil {
Return
}else {
Fmt. Println (RESP)
}
}
Image.png
However, the JSON data is not successfully parsed into the variable resp, why is this?
I just talked about it. Goland is a letter case to restrict access to the domain only the initial capitalization can be exported (can be understood as public), the son now we change the Response to this, the first letter capitalized, and then to see the results
Type Response struct {
Code Int64
MSG string
Data string
}
Image.pngimage.png
JSON data was successfully parsed out
One might notice here that the fields inside the sutruct are inconsistent with the fields in the JSON string. Here is the result of the Golang JSON parsing package auto-match (here the auto-match refers to the non-differentiated size, but the letter is still the same), do not believe us to try
Here I changed the field of the string to this
Image.png
Run result Image.png
Can the JSON field match the struct field? Of course, it is also possible.
Mapping fields can be specified by tag.
Modify the structure:
Type Response struct {
Code Int64 ' JSON: ' status '
MSG string ' JSON: ' message '
Data string ' JSON: ' Data '
}
To modify the JSON data:
Image.png
And finally, it can be resolved successfully.
Here's a summary of the writing of the STURCT export field
- 1 To resolve to a field within a struct, the field must be capitalized (that is, exported) (mandatory)
- 2 The struct field marker can match the corresponding field in the JSON data (can be ignored case) (default)
- 3 The struct field marker can be mapped by adding a tag to the corresponding field in the JSON data (that is, it can be used without a corresponding word) (optional)
- 4 Goland out of the channel, complex, and function types cannot be mapped, others can (default)
- 5 pointer types can also be mapped if the pointer is not NULL, it is automatically converted to the appropriate type (default)
- 6 inteface{} corresponds to Jsonobject, []inteface{} corresponds to Jsonarray
Json parsing
By calling the Jsonunmarshal () method, the method has two parameters, the first is the JSON data byte slice to parse, the second is the variable to resolve to, and the method failure returns the Err
Image.png
Json generation
by calling JSON. Marshal method, the method passes in a parameter, which is inteface{} (the object you want to convert), and the method returns a byte slice, and the Err
Image.png
The results are as follows Image.png