go語言之進階篇通過結構體生成json


1、通過結構體生成json

示例:

package main

import (
	"encoding/json"
	"fmt"
)

//成員變量名首字母必須大寫
type IT struct {
	Company  string
	Subjects []string
	IsOk     bool
	Price    float64
}

func main() {
	//定義一個結構體變量,同時初始化
	s := IT{"itcast", []string{"Go", "C++", "Python", "Test"}, true, 666.666}

	//編碼,根據內容生成json文本
	buf, err := json.Marshal(s)
	if err != nil {
		fmt.Println("err = ", err)
		return
	}
	fmt.Println("buf = ", string(buf))
}

執行結果:

buf =  {"Company":"itcast","Subjects":["Go","C++","Python","Test"],"IsOk":true,"Price":666.666}

  

2、根據結構體生成json

package main

import (
	"encoding/json"
	"fmt"
)

//成員變量名首字母必須大寫
type IT struct {
	Company  string
	Subjects []string
	IsOk     bool
	Price    float64
}

func main() {
	//定義一個結構體變量,同時初始化
	s := IT{"itcast", []string{"Go", "C++", "Python", "Test"}, true, 666.666}

	//編碼,根據內容生成json文本
	buf, err := json.MarshalIndent(s, "", "	") //格式化編碼
	if err != nil {
		fmt.Println("err = ", err)
		return
	}

	fmt.Println("buf = ", string(buf))
}

執行結果:

buf =  {
	"Company": "itcast",
	"Subjects": [
		"Go",
		"C++",
		"Python",
		"Test"
	],
	"IsOk": true,
	"Price": 666.666
}

  

 3、struct_tag的使用 (通過二次編碼,可以把大寫變成小寫,還可以以字符串方式輸出)

示例: 

package main

import (
	"encoding/json"
	"fmt"
)

//成員變量名首字母必須大寫
type IT struct {
	//Company  string   `json:"-"` //此字段不會輸出到屏幕

	//下面的寫法都是二次編碼,可以把大寫變成小寫
	Company  string   `json:"company"`
	Subjects []string `json:"subjects"`
	IsOk     bool     `json:"isok"`
	//轉成字符串再輸出編碼
	//IsOk  bool    `json:"string"`
	Price float64 `json:"price"`
}

func main() {
	//定義一個結構體變量,同時初始化
	s := IT{"itcast", []string{"Go", "C++", "Python", "Test"}, true, 666.666}

	//編碼,根據內容生成json文本
	buf, err := json.MarshalIndent(s, "", " ") //格式化編碼
	if err != nil {
		fmt.Println("err = ", err)
		return
	}

	fmt.Println("buf = ", string(buf))
}

執行結果:

buf =  {
 "company": "itcast",
 "subjects": [
  "Go",
  "C++",
  "Python",
  "Test"
 ],
 "isok": true,
 "price": 666.666
}

  

 


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com