码迷,mamicode.com
首页 > 编程语言 > 详细

GO语言的JSON02---反序列化

时间:2019-12-02 23:38:41      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:ring   struct   port   UNC   json对象   切片   map   byte   int   

package main

import (
	"encoding/json"
	"fmt"
)

type Human struct {
	Name string
	Age int
	Rmb float64
	Gender bool
	Hobbies []string
}

var jsonStr = `{
		"name":"梅川酷子",
		"age":40,
		"rmb":12345.123,
		"gender":false,
        "hobbies":["抽烟","喝酒","烫头"]
	}`

var jsonStr2 = `[
{
		"name":"梅川酷子",
		"age":40,
		"rmb":12345.123,
		"gender":false,
        "hobbies":["抽烟","喝酒","烫头"]
},
{
		"name":"朴成幸",
		"age":40,
		"rmb":12345.123,
		"gender":false,
        "hobbies":["抽烟","喝酒","烫头"]
}
]`

//将json反序列化为Map
func main051() {
	retMap := make(map[string]interface{})
	err := json.Unmarshal([]byte(jsonStr), &retMap)
	if err != nil{
		fmt.Println("反序列化失败,err=",err)
		return
	}
	fmt.Println(retMap)
}

//将json数组反序列化为切片
func main052() {
	retSlice := make([]map[string]interface{},0)
	err := json.Unmarshal([]byte(jsonStr2), &retSlice)
	if err != nil{
		fmt.Println("反序列化失败,err=",err)
		return
	}
	fmt.Println(retSlice)
}

/*将json对象反序列化为结构体*/
func main053() {
	human := new(Human)
	err := json.Unmarshal([]byte(jsonStr), human)
	if err != nil{
		fmt.Println("反序列化失败,err=",err)
		return
	}
	fmt.Println(human)
}

/*将json数组反序列化为切片嵌套结构体*/
func main() {
	retSlice := make([]Human, 0)
	err := json.Unmarshal([]byte(jsonStr2), &retSlice)
	if err != nil{
		fmt.Println("反序列化失败,err=",err)
		return
	}
	fmt.Println(retSlice)
}

  

GO语言的JSON02---反序列化

标签:ring   struct   port   UNC   json对象   切片   map   byte   int   

原文地址:https://www.cnblogs.com/yunweiqiang/p/11973804.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!