jsonデータを構造体に変換
2541 ワード
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
",temp)
var temp2 IT2
err = json.Unmarshal([]byte(jsonbuff),&temp2)
if err != nil{
fmt.Println("err=",err)
return
}
fmt.Printf("tmp2=%+v
",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
",key,data)
case bool:
fmt.Printf("map[%s] bool,value=%v
",key,data)
case float64:
fmt.Printf("map[%s] float64,value=%f
",key,data)
case []string:
fmt.Printf("map[%s] []string,value=%v
",key,data)
case []interface{}:
fmt.Printf("map[%s] interface{},value=%v
",key,data)
}
}
}