The JSON string is parsed to the struct
Code example
type User struct {
Name string
FansCount int64
}
// 如果反序列化的时候指定明确的结构体和变量类型
func TestJsonUnmarshal(t *testing.T) {
const jsonStream = `
{"name":"ethancai", "fansCount": 9223372036854775807}
`
var user User // 类型为User
err := JsonUnmarshal(jsonStream, &user)
if err != nil {
fmt.Println("error:", err)
}
fmt.Printf("%+v \n", user)
}
Parsing Json arrays to slices (arrays)
type Person struct {
Name string
Age int
}
type Family struct {
Persons []Person
}
// 解析多维数组
var f Family
// 模拟传输的Json数据
familyJSON := `{"Persons": [{"Name":"Elinx","Age":26}, {"Name":"Twinkle","Age":21}] }`
fmt.Println("======================")
// 解析字符串为Json
json.Unmarshal([]byte(familyJSON), &f)
Run the result
=== RUN TestJsonMash
======================
{[{Elinx 26 0001-01-01 00:00:00 +0000 UTC []} {Twinkle 21 0001-01-01 00:00:00 +0000 UTC []}]}
{"Persons":[{"Name":"Elinx","Age":26,"Birth":"0001-01-01T00:00:00Z","Children":null}
--- PASS: TestJsonMash (0.00s)
PASS
Use the struct tag to assist in building json
The fields that struct can be converted are all fields with uppercase initials, but if you want to use a key beginning with a lowercase letter in json, you can use the struttag to assist in reflection.
type Post struct {
Id int `json:"ID"`
Content string `json:"content"`
Author string `json:"author"`
Label []string `json:"label"`
}
func TestJsonMash1(t *testing.T){
postp := &Post{
2,
"Hello World",
"userB",
[]string{"linux", "shell"},
}
p, _ := json.MarshalIndent(postp, "", "\t")
fmt.Println(string(p))
}
Running result:
=== RUN TestJsonMash1
{
"ID": 2,
"content": "Hello World",
"author": "userB",
"label": [
"linux",
"shell"
]
}
--- PASS: TestJsonMash1 (0.00s)
PASS
How to use tags
- The name identified in the tag will be called the value of the key in the json data
- Tag can be set to json: "-" to indicate that this field is not converted to json data, even if the field's initials are capitalized
- If you want the name of the json key to be the character "-", you can specially treat json: "-,", that is, add a comma
- If the tag has the omitempty option, then if the value of this field is 0 values, i.e. false, 0, "", nil, etc., this field will not be converted to json
- If the type of the field is bool, string, int class, float class, and the tag has the string option, then the value of the field will be converted to a json string
Parses Json data into a structure known to struct
{
"id": 1,
"content": "hello world",
"author": {
"id": 2,
"name": "userA"
},
"published": true,
"label": [],
"nextPost": null,
"comments": [{
"id": 3,
"content": "good post1",
"author": "userB"
},
{
"id": 4,
"content": "good post2",
"author": "userC"
}
]
}
Test the code
type Post struct {
ID int64 `json:"id"`
Content string `json:"content"`
Author Author `json:"author"`
Published bool `json:"published"`
Label []string `json:"label"`
NextPost *Post `json:"nextPost"`
Comments []*Comment `json:"comments"`
}
type Author struct {
ID int64 `json:"id"`
Name string `json:"name"`
}
type Comment struct {
ID int64 `json:"id"`
Content string `json:"content"`
Author string `json:"author"`
}
func TestJsonStruct(t *testing.T){
jsonData :="{\n \"id\": 1,\n \"content\": \"hello world\",\n \"author\": {\n \"id\": 2,\n \"name\": \"userA\"\n },\n \"published\": true,\n \"label\": [],\n \"nextPost\": null,\n \"comments\": [{\n \"id\": 3,\n \"content\": \"good post1\",\n \"author\": \"userB\"\n },\n {\n \"id\": 4,\n \"content\": \"good post2\",\n \"author\": \"userC\"\n }\n ]\n}"
var post Post
// 解析json数据到post中
err := json.Unmarshal([]byte(jsonData), &post)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(post)
fmt.Println(post.Author, post.Content, post.Comments[0].Content,post.Comments[0].ID, post.Comments[0].Author )
}
=== RUN TestJsonStruct
{1 hello world {2 userA} true [] <nil> [0xc00016d1a0 0xc00016d1d0]}
{2 userA} hello world good post1 3 userB
--- PASS: TestJsonStruct (0.00s)
PASS
Welcome to pay attention to the public account: The Road to Freedom of Programmer Wealth
Insert a description of the image here
Resources
- https://www.cnblogs.com/f-ck-need-u/p/10080793.html