English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutorial Básico Golang

Controles Golang

Funções e métodos Golang

Estruturas Golang

fatias e arrays Golang

Strings Golang (String)

Ponteiros Golang

Interfaces Golang

Concorrência Golang

Exceções Golang (Error)

Miscelânea Golang

JSON em Go

Go possui suporte integrado para codificação e decodificação de JSON. Ele também suporta tipos de dados personalizados.

A função Marshal é usada para converter tipos de dados go para formato JSON.

A sintaxe da função Marshal é:

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

Marshal retorna o código JSON do valor v.

Valores booleanos são convertidos para valores booleanos JSON. Números de ponto flutuante, inteiros e números são convertidos para números JSON. As chaves de Map devem ser do tipo string, inteiro ou implementar encoding.TextMarshaler.

A decodificação de JSON é feita usando a função Unmarshal.

A sintaxe da função Unmarshal é:

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

Unmarshal decodifica valores codificados em JSON e armazena o resultado no valor apontado por v. Se v for nil ou não for um ponteiro, Unmarshal retorna InvalidUnmarshalError.

Também podemos personalizar os campos armazenados nas etiquetas do campo do struct sob a chave "json". Podemos usar o nome do campo, seguido de uma lista de opções separadas por vírgulas.

Field int 'json:"myName"' // Mostrado no JSON como a chave "myName".
Field int 'json:"myNameomitempty?'//Se o valor do campo for vazio, o campo é omitido do objeto.
Field int 'json:"-"" ////O campo é ignorado por este pacote.

Exemplo Go JSON1

package main
import "encoding"/json"
import "fmt"
func main() {
	bolType, _ := json.Marshal(false) //布尔值
	fmt.Println(string(bolType))
	intType, _ := json.Marshal("10) // 整数值
	fmt.Println(string(intType))
	fltType, _ := json.Marshal("3.14) //浮点值
	fmt.Println(string(fltType))
	strType, _ := json.Marshal("w"3codebox") // 字符串值
	fmt.Println(string(strType))
	slcA := []string{"sol", "lua", "estrela"} //切片值
	slcB, _ := json.Marshal(slcA)
	fmt.Println(string(slcB))
	mapA := map[string]int{"sol": 1, "lua": 2} //map值
	mapB, _ := json.Marshal(mapA)
	fmt.Println(string(mapB))
}

Saída:

false
10
3.14
"w"3codebox"
["sol","lua","estrela"]
{"lua":2,"sol":1}

Exemplo Go JSON2(用户定义的数据类型)

package main
import ("
	"encoding"/json"
	"fmt"
	"os"
)
type Response1 struct {
	Position int
	Planet []string
}
type Response2 struct {
	Position int  'json:"position"'
	Planet []string 'json:"planet"'
}
func main()  {
	res1A := &Response1{
		Position:   1,
		Planet: []string{"mercury", "venus", "earth"}}
	res1B, _ := json.Marshal(res1A)
	fmt.Println(string(res1B))
	res2D := &Response2{
		Position:   1,
		Planet: []string{"mercury", "venus", "earth"}}
	res2B, _ := json.Marshal(res2D)
	fmt.Println(string(res2B))
	byt := []byte('{"pi":6.13,"place":["Nova Iorque","Delhi"]}`)
	var dat map[string]interface{}
	if err := json.Unmarshal(byt, &dat); err != nil {
		panic(err)
	}
	fmt.Println(dat)
	num := dat["pi"].(float64)
	fmt.Println(num)
	strs := dat["place"].([]interface{})
	str1 := strs[0].(string)
	fmt.Println(str1)
	str := `{"Position": 1, "Planet": ["mercury", "venus"]}`
	res := Response2{}
	json.Unmarshal([]byte(str), &res)
	fmt.Println(res)
	fmt.Println(res.Planet[1])
	enc := json.NewEncoder(os.Stdout)
	d := map[string]string{"1:"mercury" , "2: "venus"}
	enc.Encode(d)
}

Saída:

{"Position":1,"Planet":["mercury","venus","earth"]}
{"position":1,"planet":["mercury","venus","earth"]}
map[pi:6.13 place:[Nova Iorque Delhi]
6.13
Nova Iorque
{1 [mercury venus]}
venus
{"1"mercury","2:"venus"