【Go】(八)Go基础 -- Json

JSON

json格式就不再赘述了,直接看看go json常用的方法

标准库encoding/json

标准库json的序列化和反序列化可以通过两种函数

  • json.Marshal和json.Unmarshal([]byte 和json互转)
  • decode返回的是steam(steam和json互转)

json.Marshal和json.Unmarshal

  • 序列化使用Marshal,反序列化使用UnMarshal
  • 使用Marshal的时候,结构体必须是可导出的(成员首字母大写)
  • 可以使用标签进行相关操作
package main

import (
	"encoding/json"
	"fmt"
	"log"
)

type Movie struct {
	Title string
	Year  int  `json:"released"`
	Color bool `json:"color,omitempty"`
}

func main() {

	movies := []Movie{
		{"title1", 2000, true},
		{"title2", 2001, true},
		{"title3", 2002, false},
	}

	data, err := json.Marshal(movies)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Printf("%s\n", data)
	// [{"Title":"title1","released":2000,"color":true},{"Title":"title2","released":2001,"color":true},{"Title":"title3","released":2002}]

	dataIndent, err := json.MarshalIndent(movies, "", "    ")
	if err != nil {
		fmt.Println(err)
	}
	fmt.Printf("%s\n", dataIndent)
	//[
	//    {
	//        "Title": "title1",
	//        "released": 2000,
	//        "color": true
	//    },
	//    {
	//        "Title": "title2",
	//        "released": 2001,
	//        "color": true
	//    },
	//    {
	//        "Title": "title3",
	//        "released": 2002
	//    }
	//]
	var m []Movie
	if err := json.Unmarshal(data, &m); err != nil {
		log.Fatalln(err)
	}
	fmt.Printf("%v", m)
	// [{title1 2000 true} {title2 2001 true} {title3 2002 false}]
}

json标签选项

  • -:不进行序列化
  • omitempy:零值或空值得时候,不对该字段进行序列化
  • Type:重新指定字段类型:json:“age,string”

json.Decode和json.Undecode

type IssueResult struct {
	TotalCount int `json:"total_count"`
	Items      []*Issue
}
type Issue struct {
	Number  int
	HTMLURL string `json:"html_url"`
	Title   string
	User    *User
}

type User struct {
	Login   string
	HTMLURL string `json:"html_url"`
}

const IssueURL = "https://api.github.com/search/issues"

func main() {

	result, err := SearchIssues([]string{"repo:golang/go"})
	if err != nil {
		fmt.Println("error")
	}
	fmt.Printf("%d issues: \n", result.TotalCount)
	for _, item := range result.Items {
		fmt.Printf("#%-5d %9.9s %.55s\n", item.Number, item.User.Login, item.Title)
	}

}

func SearchIssues(terms []string) (*IssueResult, error) {
	q := url.QueryEscape(strings.Join(terms, ""))
	resp, err := http.Get(IssueURL + "?q=" + q)
	if err != nil {
		return nil, err
	}
	if resp.StatusCode != http.StatusOK {
		resp.Body.Close()
		return nil, fmt.Errorf("error")
	}
	var result IssueResult
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		resp.Body.Close()
		return nil, err
	}
	resp.Body.Close()
	return &result, nil
}

Refs

  • https://yalantis.com/blog/speed-up-json-encoding-decoding/

你可能感兴趣的:(Go,json,golang)