天天看点

golang 学习(二十四)结构体struct 和 json之间的转换结构体struct 和 json之间的转换

结构体struct 和 json之间的转换

import (
	"encoding/json"
	"fmt"
	"math/rand"
	"testing"
)
           

struct转json字符串 json.Marshal()

type Student struct {
	Id   int
	Name string
	Age  int //如果定义为age 私有属性不能被json包访问
	Sno  string
}


//struct转json字符串
var s = Student{
	Id:   11,
	Name: "小王",
	Age:  10,
	Sno:  "n201205",
}
fmt.Printf("%#v\n", s)//demo.Student{Id:11, Name:"小王", Age:10, Sno:"n201205"}
jsonByte,_ := json.Marshal(s)
jsonStr := string(jsonByte)
fmt.Println(jsonStr)//{"Id":11,"Name":"小王","Age":10,"Sno":"n201205"}
	
           

结构体-标签 tag

type Student struct {
	Id   int    `json:"id"`
	Name string `json:"name"`
	Age  int64  `json:"age"`
	Sno  string `json:"sno"`
}
var s = Student{
		Id:   11,
		Name: "小王",
		Age:  10,
		Sno:  "n201205",
	}
	fmt.Printf("%#v\n", s) //demo.Student{Id:11, Name:"小王", Age:10, Sno:"n201205"}
	jsonByte, _ := json.Marshal(s)
	jsonStr := string(jsonByte)
	fmt.Println(jsonStr)//{"id":11,"name":"小王","age":10,"sno":"n201205"}
           

json字符串 转结构体 json.Unmarshal()

type Teacher struct {
	Id   int
	Name string
	Age  int
	Tno  string
}
var str = `{"Id":11,"Name":"王老师","Age":30,"Tno":"t201205"}`
var tea Teacher
err := json.Unmarshal([]byte(str),&tea)
if err !=nil{
	fmt.Println(err)
}
fmt.Printf("%#v\n",tea)//demo.Teacher{Id:11, Name:"王老师", Age:30, Tno:"t201205"}
fmt.Println(tea.Tno)//t201205
           

嵌套结构体

struct转json字符串

type Class struct {
	title   string
	Student []Student
}
type Student struct {
	Id   int    `json:"id"`
	Name string `json:"name"`
	Age  int64  `json:"age"`
	Sno  string `json:"sno"`
}
func TestStructJson(t *testing.T) {
	var c = Class{
		title:   "小五班",
		Student: make([]Student, 0),
	}
	for i := 1; i < 3; i++ {
		s := Student{
			Id:   i,
			Name: fmt.Sprintf("stu_%v", i),
			Age:  rand.Int63n(3) + 3,
			Sno:  fmt.Sprintf("n%05d", i),
		}
		c.Student = append(c.Student, s)
	}
	fmt.Println(c) //{小五班 [{1 stu_1 5 n00001} {2 stu_2 4 n00002}]}
	strByte, _ := json.Marshal(c)
	strJson := string(strByte)
	fmt.Println(strJson) //{"Student":[{"id":1,"name":"stu_1","age":5,"sno":"n00001"},{"id":2,"name":"stu_2","age":4,"sno":"n00002"}]}
}
           

json字符串转struct

type Class struct {
	title   string
	Student []Student
}
type Student struct {
	Id   int    `json:"id"`
	Name string `json:"name"`
	Age  int64  `json:"age"`
	Sno  string `json:"sno"`
}
func TestStructJson(t *testing.T) {
	var jsonData = `{"Student":[{"id":1,"name":"stu_1","age":5,"sno":"n00001"},{"id":2,"name":"stu_2","age":4,"sno":"n00002"}]}`
		var cla = &Class{}
		err = json.Unmarshal([]byte(jsonData), cla)
		if err != nil {
			fmt.Println(err)
		}
		fmt.Printf("%#v\n", c)//demo.Class{title:"小五班", Student:[]demo.Student{demo.Student{Id:1, Name:"stu_1", Age:5, Sno:"n00001"}, demo.Student{Id:2, Name:"stu_2", Age:4, Sno:"n00002"}}}
}