1. 程式人生 > >golang json序列化

golang json序列化

odi truct str 意義 marshal UNC 序列 分享圖片 ola

結構體序列化

func main() {
	var j = js{
		Name:  "zhangsan",
		Age:   16,
		Sal:   1500.3,
		Intro: "aihao lanqiu",
	}

	json1, _ := json.Marshal(j)
	fmt.Println(string(json1))
	mp()
	slic()
}

map序列化

func mp() {
	var a = map[string]interface{}{
		"Name": "lisi",
		"Age":  16,
		"Sal":  22.33,
	}

	js, _ := json.Marshal(a)
	fmt.Println(string(js))
}

切片序列化

func slic() {
	var slice = []map[string]interface{}{
		map[string]interface{}{
			"Name": "lisi",
			"Age":  16,
			"Sal":  22.33,
		},
		map[string]interface{}{
			"Name": "zhangsan",
			"Age":  22,
			"Sal":  1122.33,
		},
	}

	js, _ := json.Marshal(slice)
	fmt.Println(string(js))
}

技術分享圖片

切片序列化後返回的是一個數組,因為切片中包含兩個元素,即切片包含兩個切片故為一個數組

package main

import (
	"encoding/json"
	"fmt"
)

type js struct {
	Name  string
	Age   int
	Sal   float32
	Intro string
}

func mp() {
	var a = map[string]interface{}{
		"Name": "lisi",
		"Age":  16,
		"Sal":  22.33,
	}

	js, _ := json.Marshal(a)
	fmt.Println(string(js))
}

func slic() {
	var slice = []map[string]interface{}{
		map[string]interface{}{
			"Name": "lisi",
			"Age":  16,
			"Sal":  22.33,
		},
		map[string]interface{}{
			"Name": "zhangsan",
			"Age":  22,
			"Sal":  1122.33,
		},
	}

	js, _ := json.Marshal(slice)
	fmt.Println(string(js))
}

func main() {
	var j = js{
		Name:  "zhangsan",
		Age:   16,
		Sal:   1500.3,
		Intro: "aihao lanqiu",
	}

	json1, _ := json.Marshal(j)
	fmt.Println(string(json1))
	mp()
	slic()
}

基礎類型結構化

無意義

package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	var a = 1
	var s = "abc"

	a1, _ := json.Marshal(a)
	s1, _ := json.Marshal(s)

	fmt.Println(string(a1))
	fmt.Println(string(s1))
}

技術分享圖片

golang json序列化