Golang encoding and parsing Json

table of Contents

1. Coding: func Marshal 

2. Analysis: func Unmarshal


Two functions Marshal and Unmarshal are provided in the Golang encoding/json package, which are used to encode and decode (parse) data in Json format respectively.

1. Coding: func Marshal 

func Marshal(v interface{}) ([]byte, error)

Function: Return the Json data encoded by v, pay attention to []byte, for example:

package main

import (
	"encoding/json"
	"fmt"
)

type Students struct {
	Name   string `Json:"name"`
	Height int    `Json:"height"`
	Sex    string `Json:"sex"`
}

type Teachers struct {
	Name   string `Json:"name"`
	Height int    `Json:"height"`
	Sex    string `Json:"sex"`
}

type School struct {
	Name    string     `Json:"name"`
	Area    int        `Json:"area"`
	Student []Students `Json:"student"`
	Teacher []Teachers `Json:"teacher"`
}

//initAssignment 初始化School
func initAssignment() School {
	student := []Students{
		{"张三", 180, "男"},
		{"王丽", 165, "女"},
	}
	teacher := []Teachers{
		{"李四", 180, "女"},
		{"王五", 177, "男"},
	}
	school := School{"中关村大学", 1024, student, teacher}

	return school
}

func main() {
	school := initAssignment()
	schoolJson, err := json.Marshal(school)
	if err != nil {
		fmt.Println("Umarshal Error:" + err.Error())
		return
	}
	fmt.Println("schoolJson:", string(schoolJson))
}

In the above example, there are three structures School, Students, and Teacher. Among them, School contains the latter two, instantiate a School type and convert it to a Json type.

Output:

[root@localhost gotest]# go run main.go 
schoolJson: {"Name":"中关村大学","Area":1024,"Student":[{"Name":"张三","Height":180,"Sex":"男"},{"Name":"王丽","Height":165,"Sex":"女"}],"Teacher":[{"Name":"李四","Height":180,"Sex":"女"},{"Name":"王五","Height":177,"Sex":"男"}]}
[root@localhost gotest]#

This is not very intuitive, look at the following form:

{
    "Name": "中关村大学",
    "Area": 1024,
    "Student": [
        {
            "Name": "张三",
            "Height": 180,
            "Sex": "男"
        },
        {
            "Name": "王丽",
            "Height": 165,
            "Sex": "女"
        }
    ],
    "Teacher": [
        {
            "Name": "李四",
            "Height": 180,
            "Sex": "女"
        },
        {
            "Name": "王五",
            "Height": 177,
            "Sex": "男"
        }
    ]
}

2. Analysis: func Unmarshal

func Unmarshal(data []byte, v interface{}) error

Function: Unmarshal parses the JSON data and stores the result in v. If v is nil or not a pointer, Unmarshal returns InvalidUnmarshalError, for example:

package main

import (
	"encoding/json"
	"fmt"
)

type Students struct {
	Name   string `Json:"name"`
	Height int    `Json:"height"`
	Sex    string `Json:"sex"`
}

type Teachers struct {
	Name   string `Json:"name"`
	Height int    `Json:"height"`
	Sex    string `Json:"sex"`
}

type School struct {
	Name    string     `Json:"name"`
	Area    int        `Json:"area"`
	Student []Students `Json:"student"`
	Teacher []Teachers `Json:"teacher"`
}

func main() {
	var school School
	strJson := `{"name":"中关村大学","area":1024,"student":[{"name":"张三","height":180,"sex":"男"},{"name":"王丽","height":165,"sex":"女"}],"teacher":[{"name":"李四","height":180,"sex":"女"},{"name":"王五","height":177,"sex":"男"}]}`
	err := json.Unmarshal([]byte(strJson), &school) //注意:第二个参数需要传递地址
	if err != nil {
		fmt.Println("Umarshal Error:" + err.Error())
		return
	}
	fmt.Printf("%#v\n", school)
	fmt.Println(school.Name, school.Area)
}

Output:

[root@localhost gotest]# go run main.go 
main.School{Name:"中关村大学", Area:1024, Student:[]main.Students{main.Students{Name:"张三", Height:180, Sex:"男"}, main.Students{Name:"王丽", Height:165, Sex:"女"}}, Teacher:[]main.Teachers{main.Teachers{Name:"李四", Height:180, Sex:"女"}, main.Teachers{Name:"王五", Height:177, Sex:"男"}}}
中关村大学 1024
[root@localhost gotest]#

It should be noted here that the first letter of the variable name in the structure should be capitalized so that other packages can access the variable of the structure. You can parse the corresponding variable in Json by adding `Json:"variable name"` after the variable.

Reference link:

[1] https://golang.org/pkg/encoding/json/

Guess you like

Origin blog.csdn.net/u011074149/article/details/110291423