码迷,mamicode.com
首页 > Web开发 > 详细

json数据转换成结构体

时间:2019-12-21 12:00:13      阅读:91      评论:0      收藏:0      [点我收藏+]

标签:com   val   oat   ice   func   company   创建   type   err   

package main

import (
	"encoding/json"
	"fmt"
)

type IT1 struct {
	Company string `json:"company"`
	Subjects []string `json:"subjects"`
	IsOk bool  	`json:"isok"`
	Price float64 `json:"price"`
}

type IT2 struct {
	Company string `json:"company"`

}

func main(){
	jsonbuff :=`{
	"company": "zhczGO",
	"isok": true,
	"price": 99,
	"subjects": [
		"go",
		"fabric",
		"python",
		"Test"
	]
}`

var temp IT1
err :=json.Unmarshal([]byte(jsonbuff),&temp)
if err != nil{
	fmt.Println("err=",err)
	return
}
//fmt.Println("temp=",temp)
fmt.Printf("tmp=%+v\n",temp)

var temp2 IT2
err = json.Unmarshal([]byte(jsonbuff),&temp2)
if err != nil{
	fmt.Println("err=",err)
	return
}
fmt.Printf("tmp2=%+v\n",temp2)

}

  

package main

import (
	"encoding/json"
	"fmt"
)

func main()  {
	jsonbuff :=`{
	"company": "zhczGO",
	"isok": true,
	"price": 99,
	"subjects": [
		"go",
		"fabric",
		"python",
		"Test"
	]
}`

  //创建一个map
  m := make(map[string]interface{},4)
  err := json.Unmarshal([]byte(jsonbuff),&m) //一定要是地址

  if err != nil{
     fmt.Println("err=",err)
     return
  }
  fmt.Printf("m=%+v/n",m)

  //var str string
  //str = m["company"]//err 无法转换

  //类型断言
	for key,value := range m  {
		switch data := value.(type) {
		case string:
			//str = data
			fmt.Printf("map[%s]的值类型为string,value=%s\n",key,data)
		case bool:
			fmt.Printf("map[%s]的值类型为bool,value=%v\n",key,data)
		case float64:
			fmt.Printf("map[%s]的值类型为float64,value=%f\n",key,data)
		case []string:
			fmt.Printf("map[%s]的值类型为[]string,value=%v\n",key,data)
		case []interface{}:
			fmt.Printf("map[%s]的值类型为interface{},value=%v\n",key,data)
		}
	}

	
}

  

json数据转换成结构体

标签:com   val   oat   ice   func   company   创建   type   err   

原文地址:https://www.cnblogs.com/dqh123/p/12076319.html

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