Codificação Golang e análise de Json

índice

1. Codificação: func Marshal 

2. Análise: func Unmarshal


Duas funções Marshal e Unmarshal são fornecidas no pacote Golang encoding / json, que são usadas para codificar e decodificar (analisar) dados no formato Json, respectivamente.

1. Codificação: func Marshal 

função Marshal (v interface {}) ([] byte, erro)

Função: Retorne os dados Json codificados por v, observe que é byte [], por exemplo:

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))
}

No exemplo acima, existem três estruturas Escola, Alunos e Professor.Entre elas, Escola contém as duas últimas, instancia um tipo Escola e converte-o em um tipo Json.

Resultado:

[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]#

Isso não é muito intuitivo, observe o seguinte formulário:

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

2. Análise: func Unmarshal

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

Função: Unmarshal analisa os dados JSON e armazena o resultado em v. Se v for nulo ou não for um ponteiro, Unmarshal retornará InvalidUnmarshalError, por exemplo:

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)
}

Resultado:

[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]#

Deve-se notar aqui que a primeira letra do nome da variável na estrutura deve ser maiúscula para que outros pacotes possam acessar a variável da estrutura. Você pode analisar a variável correspondente em Json adicionando `Json:" nome da variável "` após a variável.

Link de referência:

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

Acho que você gosta

Origin blog.csdn.net/u011074149/article/details/110291423
Recomendado
Clasificación